Java - Sorting Algorithm - QuickSort Recursive
We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. I have explained here on how mergesort algorithm works in recursive mode.
The recusrive approach requires creatiion multi branch recursion by dividing the number of elements by two. For each time when partition method is called, the pivot is placed at the correct position meaning all the elements to the left are less than the pivot value and all the elements to right are greater than the pivot value.
Click here for Java BubbleSort Algorithm
Click here for Java InsertionSort Algorithm
Click here for Java MergeSort Recursive Algorithm
Click here for Java MergeSort Iterative Algorithm
Click here for Java QuickSort Recursive Algorithm
Click here for Java QuickSort Iterative Algorithm
The complete program and test run output are given below:
Source Code
import java.io.*;
import java.util.*;
import java.lang.*;
class QuickSort {
public static int Partition(int[] numbers, int left, int right)
{
int pivot = numbers[left];
while (true)
{
while (numbers[left] < pivot)
left++;
while (numbers[right] > pivot)
right--;
if (left < right)
{
int temp = numbers[right];
numbers[right] = numbers[left];
numbers[left] = temp;
}
else
{
return right;
}
}
}
public static void QuickSort_Recursive(int[] arr, int left, int right)
{
// For Recusrion
if(left < right)
{
int pivot = Partition(arr, left, right);
if(pivot > 1)
QuickSort_Recursive(arr, left, pivot - 1);
if(pivot + 1 < right)
QuickSort_Recursive(arr, pivot + 1, right);
}
}
public static void main(String[] args)
{
int[] numbers = { 3, 8, 7, 5, 2, 1, 9, 6, 4 };
int len = 9;
System.out.println("QuickSort By Recursive Method");
QuickSort_Recursive(numbers, 0, len - 1);
for (int i = 0; i < 9; i++)
System.out.println(numbers[i]);
System.out.println();
}
}
Output
QuickSort By Recursive Method
1
2
3
4
5
6
7
8
9
Press any key to continue . . .
|