|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +class Quicksort { |
| 4 | + |
| 5 | + // method to find the partition position |
| 6 | + static int partition(int array[], int low, int high) { |
| 7 | + |
| 8 | + // choose the rightmost element as pivot |
| 9 | + int pivot = array[high]; |
| 10 | + |
| 11 | + // pointer for greater element |
| 12 | + int i = (low - 1); |
| 13 | + |
| 14 | + // traverse through all elements |
| 15 | + // compare each element with pivot |
| 16 | + for (int j = low; j < high; j++) { |
| 17 | + if (array[j] <= pivot) { |
| 18 | + |
| 19 | + // if element smaller than pivot is found |
| 20 | + // swap it with the greater element pointed by i |
| 21 | + i++; |
| 22 | + |
| 23 | + // swapping element at i with element at j |
| 24 | + int temp = array[i]; |
| 25 | + array[i] = array[j]; |
| 26 | + array[j] = temp; |
| 27 | + } |
| 28 | + |
| 29 | + } |
| 30 | + |
| 31 | + // swapt the pivot element with the greater element specified by i |
| 32 | + int temp = array[i + 1]; |
| 33 | + array[i + 1] = array[high]; |
| 34 | + array[high] = temp; |
| 35 | + |
| 36 | + // return the position from where partition is done |
| 37 | + return (i + 1); |
| 38 | + } |
| 39 | + |
| 40 | + static void quickSort(int array[], int low, int high) { |
| 41 | + if (low < high) { |
| 42 | + |
| 43 | + // find pivot element such that |
| 44 | + // elements smaller than pivot are on the left |
| 45 | + // elements greater than pivot are on the right |
| 46 | + int pi = partition(array, low, high); |
| 47 | + |
| 48 | + // recursive call on the left of pivot |
| 49 | + quickSort(array, low, pi - 1); |
| 50 | + |
| 51 | + // recursive call on the right of pivot |
| 52 | + quickSort(array, pi + 1, high); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// Main class |
| 58 | +class Main { |
| 59 | + public static void main(String args[]) { |
| 60 | + |
| 61 | + int[] data = { 8, 7, 2, 1, 0, 9, 6 }; |
| 62 | + System.out.println("Unsorted Array"); |
| 63 | + System.out.println(Arrays.toString(data)); |
| 64 | + |
| 65 | + int size = data.length; |
| 66 | + |
| 67 | + // call quicksort() on array data |
| 68 | + Quicksort.quickSort(data, 0, size - 1); |
| 69 | + |
| 70 | + System.out.println("Sorted Array in Ascending Order "); |
| 71 | + System.out.println(Arrays.toString(data)); |
| 72 | + } |
| 73 | +} |
0 commit comments