Quick Sort
public class QuickSort {
static int[] a;
static int size;
public static void main(String[] args) {
a= new int[]{38, 19, 67, 30, 18};
size = a.length;
Sort(0, size - 1);
System.out.println("Sorted array is :");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
private static void Sort(int low, int high) {
int i = low, j = high;
int pivot = a[low + (high - low) / 2]; // Get the pivot element from the middle of the list
while (i <= j) { // Divide into two lists
while (a[i] < pivot) { /*If the current value from the left list is smaller then the pivot
element then get the next element from the left list*/
i++;
}
while (a[j] > pivot) { /* If the current value from the right list is larger then the pivot
element then get the next element from the right list*/
j--;
}
if (i <= j) { // If we have found a values in the left list which is larger than
// the pivot element and if we have found a value in the right list
exchange(i,j); // which is smaller then the pivot element then we exchange the values.
i++; // As we are done we can increase i and j
j--;
}
}
if (low < j) { // Recursion
Sort(low, j);
}
if (i < high) {
Sort(i, high);
}
}
private static void exchange(int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Output:
Sorted array is :
18
19
30
38
67