How to Sort an Array in Scala?

Sorting arrays effectively is essential for many applications, regardless of whether you’re working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situations.

This article will examine the nuances of sorting arrays in Scala and the different approaches and techniques used to do this task successfully.

Table of Content

  • What is Sorting in an Array?
  • Using ‘sortWith’ Method
  • Using ‘sorted()’ Method
  • Using ‘sortBy()’ Method
  • Sorting Arrays of Objects
  • Sorting Arrays in Reverse Order
  • Conclusion
  • FAQs

What is Sorting in an Array?

Rearranging an array’s contents in a certain order, usually according to some sort of criterion (e.g., numerical value, alphabetical order, or custom comparison function), is known as sorting.

  1. Sorting is done to force an appropriate order on the array’s items so that searching, retrieving, and analyzing the data is made simpler.
  2. Programming sorting of an array entails pairwise comparisons and rearranging of the members to achieve the desired order.
  3. Depending on the needs of the application, either ascending or descending order might be used for this.
  4. The sorted array keeps all of the original array’s items but arranges them to make data handling and retrieval more efficient.

Using ‘sortWith’ Method

You can specify your own custom sorting logic using the ‘sortWith()’ method. It requires a function to compare two elements, and it outputs a boolean representing the order of sorting.

Below is the Scala program to implement the approach:

Scala
val names = Array("Alice", "Bob", "Charlie", "David")

// Sort by name length (ascending)
val sortedNames = names.sortWith(_.length < _.length)

// Output: Bob, Alice, David, Charlie
println(sortedNames.mkString(", ")) 

Output:

Using ‘sortWith’ Method

Using ‘sorted()’ Method

The ‘sorted()’ method returns a new sorted array without altering the original array, thus you can use it if you would rather not change the original one.

Below is the Scala program to implement the approach:

Scala
val arr = Array(3, 1, 4, 1, 5, 9, 2, 6, 5)

// Returns a new sorted array
val sortedArr = arr.sorted 

// Output: 1, 1, 2, 3, 4, 5, 5, 6, 9
println(sortedArr.mkString(", ")) 

Output:

Using ‘sorted()’ Method

Using ‘sortBy()’ Method

Sorting can be done using a custom comparison function with the help of the ‘sortBy()’ method in Scala’s collections package. Using a function that associates array members with keys, this technique sorts the array according to these keys.

Below is the Scala program to implement the approach:

Scala
val arr = Array("apple", "banana", "orange", "grape")

// Sort by length of strings
val sortedArr = arr.sortBy(_.length) 

// Output: apple, grape, banana, orange
println(sortedArr.mkString(", ")) 

Output:

Using ‘sortBy()’ Method

Sorting Arrays of Objects

You can use the sortBy() method in conjunction with a custom comparison function that takes an object’s key and uses it to sort arrays of custom objects.

Below is the Scala program to implement the approach:

Scala
case class Person(name: String, age: Int)
val people = Array(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20))
val sortedPeople = people.sortBy(_.age) // Sort by age
println(sortedPeople.mkString(", ")) // Output: Person(Charlie,20), Person(Alice,25), Person(Bob,30)

Output:

Sorting Arrays of Objects

Sorting Arrays in Reverse Order

After sorting an array using one of the above ways, you may use the ‘reverse’ method to sort the array in the opposite order.

Below is the Scala program to implement the approach:

Scala
val arr = Array(3, 1, 4, 1, 5, 9, 2, 6, 5)

// Sort in descending order
val reversedSortedArr = arr.sorted.reverse

// Output: 9, 6, 5, 5, 4, 3, 2, 1, 1
println(reversedSortedArr.mkString(", ")) 

Output:

Sorting Arrays in Reverse Order

Conclusion

Because Scala includes built-in methods, sorting arrays in the language is simple. Scala offers versatile options to match your needs, whether you need to sort custom objects, arrays of primitive types, or custom sorting criteria. You may easily manage and modify arrays in your Scala applications by utilizing these techniques.

FAQs based on How to Sort an Array in Scala?

1. Why does ‘sort()’ not work with arrays of primitive types in Scala ?

Since the ‘sort()’ method is designed for arrays of objects, it cannot be used with arrays of primitive types, such as ‘Array[Int]’. The ‘sorted’ method is what you should use to sort arrays of primitives.

2. How do I sort an array of strings in case-insensitive order in Scala ?

‘SortBy’ can be used with a function that changes a string’s case, either upper or lower. ‘arr.sortBy(_.toLowerCase)’, for instance, sorts strings without regard to case.

3. Is it possible to sort only a part of an array in Scala ?

Yes, you can slice an array and then sort the sliced portion. var partSortedArr = arr.slice(1, 5), for instance a subarray is ordered from index 1 to index 4.

4. What libraries or imports are needed to sort arrays in Scala ?

All of the required sorting methods are included in the standard library of Scala. You only need to make sure that your code includes import scala.Array ; no other libraries are required in case you’re operating in a setting where explicit imports are necessary.

5. How do I sort an array in Scala based on a custom ordering ?

The ‘sortWith’ method, which offers a customizable comparison mechanism, can be utilised. ‘Arr.sortWith(_ > _)’, for instance, uses a custom condition to sort the array in descending order.



Contact Us