Scala Program to Implement Quick Sort

Scala Program to Implement Quick Sort

Quick Sort is one of the most famous sorting algorithms in computer science, known for its impressive speed and efficiency when working with large amounts of data. Many developers choose it because it handles sorting tasks in a smart way by dividing data into smaller pieces, sorting each piece separately, and then bringing everything back together. This makes it both elegant and powerful, especially in situations where performance truly matters.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

The idea behind Quick Sort is simple but effective. At the heart of the algorithm is a “pivot,” which acts like a guide for separating values into smaller and larger groups. With each division, the data becomes more organized until the final sorted order appears. This style of problem-solving is useful in many real projects, from analytics software to search systems. For beginners, learning Quick Sort in Scala is a great step toward understanding how fast algorithms work and why efficient sorting is such an important part of programming.

Program 1: Basic Recursive Quick Sort

This first version shows the classic recursive Quick Sort approach. It picks a pivot, splits the list into smaller and larger values, and then applies the same logic to each side.

object QuickSortBasic {

  def quickSort(arr: List[Int]): List[Int] = {

    if (arr.length <= 1) arr

    else {

      val pivot = arr(arr.length / 2)
      val smaller = arr.filter(_ < pivot)
      val equal = arr.filter(_ == pivot)
      val larger = arr.filter(_ > pivot)

      quickSort(smaller) ::: equal ::: quickSort(larger)

    }

  }

  def main(args: Array[String]): Unit = {

    val data = List(9, 4, 7, 3, 8, 2)
    println("Sorted List: " + quickSort(data))

  }

}

This version works by choosing the middle element as the pivot. The list is split into groups around the pivot, and then each group is sorted through recursive calls. Beginners find this method clear because the steps mirror the natural explanation of Quick Sort. It is also easy to modify or adapt for other types of data later.

Program 2: Quick Sort Using Arrays and Partitioning

This program uses arrays to help learners see how Quick Sort works with fixed-size, index-based structures. It shows how partitioning is done manually.

object QuickSortArray {

  def quickSort(arr: Array[Int], low: Int, high: Int): Unit = {

    if (low < high) {

      val pivotIndex = partition(arr, low, high)

      quickSort(arr, low, pivotIndex - 1)
      quickSort(arr, pivotIndex + 1, high)

    }

  }

  def partition(arr: Array[Int], low: Int, high: Int): Int = {

    val pivot = arr(high)
    var i = low - 1

    for (j <- low until high) {

      if (arr(j) <= pivot) {

        i += 1
        val temp = arr(i)
        arr(i) = arr(j)
        arr(j) = temp

      }

    }

    val temp = arr(i + 1)
    arr(i + 1) = arr(high)
    arr(high) = temp

    i + 1

  }

  def main(args: Array[String]): Unit = {

    val data = Array(5, 1, 9, 3, 7)

    quickSort(data, 0, data.length - 1)

    println("Sorted Array: " + data.mkString(", "))

  }

}

Here the rightmost element becomes the pivot, and values are swapped carefully to make sure smaller ones move to the front. This gives a clear picture of how Quick Sort works internally without using built-in filtering. It helps beginners understand index movement, swapping, and how partitioning affects the entire algorithm.

Program 3: Quick Sort Using Mutable Buffers

This approach uses ArrayBuffer, giving learners a more flexible structure that behaves like a dynamic array.

import scala.collection.mutable.ArrayBuffer

object QuickSortBuffer {

  def quickSort(buffer: ArrayBuffer[Int], low: Int, high: Int): Unit = {

    if (low < high) {

      val pivotIndex = partition(buffer, low, high)

      quickSort(buffer, low, pivotIndex - 1)
      quickSort(buffer, pivotIndex + 1, high)

    }

  }

  def partition(buffer: ArrayBuffer[Int], low: Int, high: Int): Int = {

    val pivot = buffer(high)
    var i = low - 1

    for (j <- low until high) {

      if (buffer(j) <= pivot) {

        i += 1
        val temp = buffer(i)
        buffer(i) = buffer(j)
        buffer(j) = temp

      }

    }

    val temp = buffer(i + 1)
    buffer(i + 1) = buffer(high)
    buffer(high) = temp

    i + 1

  }

  def main(args: Array[String]): Unit = {

    val data = ArrayBuffer(20, 7, 14, 3, 10)

    quickSort(data, 0, data.length - 1)

    println("Sorted Buffer: " + data.mkString(", "))

  }

}

This version helps beginners understand Quick Sort while working with a structure that grows and shrinks. It is useful in real-world situations where data may change frequently. Learning this approach builds confidence for working with dynamic collections.

Program 4: Quick Sort With Strings

This final program shows how Quick Sort can sort words or other text data, not just numbers.

object QuickSortStrings {

  def quickSort(arr: List[String]): List[String] = {

    if (arr.length <= 1) arr
    else {

      val pivot = arr(arr.length / 2)
      val smaller = arr.filter(_ < pivot)
      val equal = arr.filter(_ == pivot)
      val larger = arr.filter(_ > pivot)

      quickSort(smaller) ::: equal ::: quickSort(larger)

    }

  }

  def main(args: Array[String]): Unit = {

    val data = List("apple", "mango", "banana", "grape")
    println("Sorted Words: " + quickSort(data))

  }

}

This version behaves just like the earlier list-based Quick Sort, showing how flexible the algorithm can be. Sorting words helps beginners understand that any type with a natural order can be used with Quick Sort. It is a simple yet powerful demonstration of how algorithms adapt to different data.

Frequently Asked Questions (FAQ)

This section clears common doubts many learners have about Quick Sort in Scala. The answers are kept short and easy to follow, helping beginners feel more confident as they study the algorithm.

Q1: Why is Quick Sort considered one of the fastest sorting algorithms?
It divides data into smaller groups and sorts each part recursively, which often results in very fast performance in everyday use.

Q2: Does Quick Sort always use a pivot?
Yes, the pivot is at the center of how the algorithm works because it guides how the data is split.

Q3: Can Quick Sort handle strings or custom objects?
Yes, as long as the values can be compared, Quick Sort can arrange them in order.

Q4: Is Quick Sort good for very large datasets?
In most real situations, yes. However, its speed depends on choosing a balanced pivot.

Q5: Does Quick Sort always use recursion?
Recursive versions are common, but iterative versions are also possible. Both work well in Scala.

Conclusion

Quick Sort is a wonderful algorithm for beginners who want to learn how fast sorting really works. It teaches valuable ideas such as pivot selection, partitioning, recursion, and efficient data handling. Scala handles Quick Sort beautifully, whether you use lists, arrays, or buffers.

By exploring the different programs in this guide, you gain a deeper understanding of how Quick Sort behaves in various forms. Keep experimenting with new inputs, new pivot choices, and even new data types. Each experiment will strengthen your skills and help you grow as a Scala programmer.

Scroll to Top