Home > Enterprise >  Is this the correct way to sort generic type?
Is this the correct way to sort generic type?

Time:08-17

I am just trying to write a bubble sorting code using generic. I am not sure whether this is the right approach to writing sorting logic for generic. Here "if" condition is giving compile time error. For any particular type, this is working fine. How can I resolve this and program it in a better way? Thanks in advance.

def sortAny[T](list: Array[T]): Array[T] = {
var count = 0
while (count < list.length) {
  for (count <- 0 until list.length - 1) {
    if (list(count) > list(count   1)) {
      val temp = list(count)
      list(count) = list(count   1)
      list(count   1) = temp
    }
  }
  count = count   1
}

list

}

CodePudding user response:

def sortAny[T <% Ordered[T]](list: Array[T]): Array[T] = {
var count = 0
while (count < list.length) {
  for (count <- 0 until list.length - 1) {
    if (list(count) > list(count   1)) {
      val temp = list(count)
      list(count) = list(count   1)
      list(count   1) = temp
    }
  }
  count = count   1
  }

list
}

Output will be

sortAny: [T](list: Array[T])(implicit evidence$1: T => Ordered[T])Array[T]

T <% S (a view bound) says that type T must be convertible to S, so it has to be either a subtype of S or have implicit conversion defined.

  • Related