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.
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.
Output:
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