|
| 1 | +// Java program for implementation of QuickSort |
| 2 | +class QuickSort { |
| 3 | + /* |
| 4 | + * This function takes last element as pivot, places the pivot element at its |
| 5 | + * correct position in sorted array, and places all smaller (smaller than pivot) |
| 6 | + * to left of pivot and all greater elements to right of pivot |
| 7 | + */ |
| 8 | + int partition(int arr[], int low, int high) { |
| 9 | + int pivot = arr[high]; |
| 10 | + int i = (low - 1); // index of smaller element |
| 11 | + for (int j = low; j < high; j++) { |
| 12 | + // If current element is smaller than the pivot |
| 13 | + if (arr[j] < pivot) { |
| 14 | + i++; |
| 15 | + |
| 16 | + // swap arr[i] and arr[j] |
| 17 | + int temp = arr[i]; |
| 18 | + arr[i] = arr[j]; |
| 19 | + arr[j] = temp; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // swap arr[i+1] and arr[high] (or pivot) |
| 24 | + int temp = arr[i + 1]; |
| 25 | + arr[i + 1] = arr[high]; |
| 26 | + arr[high] = temp; |
| 27 | + |
| 28 | + return i + 1; |
| 29 | + } |
| 30 | + |
| 31 | + /* |
| 32 | + * The main function that implements QuickSort() arr[] --> Array to be sorted, |
| 33 | + * low --> Starting index, high --> Ending index |
| 34 | + */ |
| 35 | + void sort(int arr[], int low, int high) { |
| 36 | + if (low < high) { |
| 37 | + /* |
| 38 | + * pi is partitioning index, arr[pi] is now at right place |
| 39 | + */ |
| 40 | + int pi = partition(arr, low, high); |
| 41 | + |
| 42 | + // Recursively sort elements before |
| 43 | + // partition and after partition |
| 44 | + sort(arr, low, pi - 1); |
| 45 | + sort(arr, pi + 1, high); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + /* A utility function to print array of size n */ |
| 50 | + static void printArray(int arr[]) { |
| 51 | + int n = arr.length; |
| 52 | + for (int i = 0; i < n; ++i) |
| 53 | + System.out.print(arr[i] + " "); |
| 54 | + System.out.println(); |
| 55 | + } |
| 56 | + |
| 57 | + // Driver program |
| 58 | + public static void main(String args[]) { |
| 59 | + int arr[] = { 10, 7, 8, 9, 1, 5 }; |
| 60 | + int n = arr.length; |
| 61 | + |
| 62 | + QuickSort ob = new QuickSort(); |
| 63 | + ob.sort(arr, 0, n - 1); |
| 64 | + |
| 65 | + System.out.println("sorted array"); |
| 66 | + printArray(arr); |
| 67 | + } |
| 68 | +} |
| 69 | +/* This code is contributed by Rajat Mishra */ |
0 commit comments