Quick Sort Recursive Implementation In Java
Sorting Techniques
import java.io.*;
class QuickSortImple
{
static void swap(int data[], int left, int right)
{
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
private static int partition(int data[], int left, int right)
{
while(true)
{
while(left < right && data[left] < data[right])
right--;
if(left<right)
{
swap(data, left, right);
left++;
}
else
return left;
while(left < right && data[left] < data[right])
left++;
if(left<right)
{
swap(data, left, right);
right--;
}
else
return right;
}
}
private static void quickSortRecursive(int data[], int left, int right)
{
int pivot;
if(left >= right) return;
pivot = partition(data,left,right);
quickSortRecursive(data,left,pivot-1);
quickSortRecursive(data,pivot+1,right);
}
public static void quickSortP(int data[], int n)
{
quickSortRecursive(data,0,n-1);
}
}
class QuickSort
{
public static void main(String args[])
{
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the array to be sorted");
int data[]=new int[10];
try
{
for(int i=0;i<10;i++)
data[i]=Integer.parseInt(in.readLine());
}
catch(Exception e) {}
QuickSortImple.quickSortP(data, 10);
System.out.println("Sorted array:");
for(int i=0;i<10;i++)
System.out.println(+data[i]);
}
}
-------------------------------Output------------------------------------------
---------------------------------------------------------------------------------
Enter the array to be sorted
4
7
12
78
34
7
19
1
6
35
Sorted array:
1
4
6
7
7
12
19
34
35
78
You Might Also Like :