Q:

Scala program to sort an array in ascending order using quicksort with recursion

belongs to collection: Scala Array Programs

0

Here, we will create an array of integers and then we will sort the created array using quicksort with recursion.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to sort an array in ascending order using quicksort with recursion is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to sort an array 
// using quicksort with recursion

object Sample {  
    def QuickSort(arr:Array[Int], first:Int, last:Int){
        var pivot:Int=0
        var temp:Int=0
        var i:Int=0
        var j:Int=0
        
        if(first < last)
        {
            pivot = first
            i = first
            j = last
            
            while(i<j)
            {
                while(arr(i)<=arr(pivot) && i<last)
                {
                    i=i+1;
                }
                while (arr(j) > arr(pivot))
                {
                    j = j - 1
                }
                if(i < j)
                {
                    temp = arr(i)
                    arr(i) = arr(j)
                    arr(j) = temp
                }
            }
            temp = arr(pivot)
            arr(pivot) = arr(j)
            arr(j) = temp
            QuickSort(arr, first, j - 1)
            QuickSort(arr, j + 1, last)
        }
    }
    
    def main(args: Array[String]) {  
        var IntArray = Array(31,15,42,14,23)
        var i:Int=0
        
        QuickSort(IntArray,0,4);
        
        i=0;
        println("Sorted Array: ");
        while(i<5)
        {
            printf("%d ",IntArray(i));
            i=i+1;
        }
        println()
    }
}

Output:

Sorted Array: 
14 15 23 31 42 

Explanation:

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

Here, we defined a method QuickSort() to sort an array in ascending order. And, we use recursion to use apply the quick sort process effectively. Using the QuickSort() method, we divide the given array into small sub-arrays. Then we sort sub-arrays recursively.

In the main() function, we created an array IntArray that contains 5 integer items. Then we sorted the created array in ascending order using quicksort. After that, we printed the sorted array on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to sort an array in ascending order ... >>
<< Scala program to sort an array in descending order...