|
| 1 | +// Quick sort in Java |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +class QuickSort { |
| 6 | + |
| 7 | + // Function to partition the array on the basis of pivot element |
| 8 | + int partition(int array[], int low, int high) { |
| 9 | + |
| 10 | + // Select the pivot element |
| 11 | + int pivot = array[high]; |
| 12 | + int i = (low - 1); |
| 13 | + |
| 14 | + // Put the elements smaller than pivot on the left and |
| 15 | + // greater than pivot on the right of pivot |
| 16 | + for (int j = low; j < high; j++) { |
| 17 | + if (array[j] <= pivot) { |
| 18 | + i++; |
| 19 | + int temp = array[i]; |
| 20 | + array[i] = array[j]; |
| 21 | + array[j] = temp; |
| 22 | + } |
| 23 | + } |
| 24 | + int temp = array[i + 1]; |
| 25 | + array[i + 1] = array[high]; |
| 26 | + array[high] = temp; |
| 27 | + return (i + 1); |
| 28 | + } |
| 29 | + |
| 30 | + void quickSort(int array[], int low, int high) { |
| 31 | + if (low < high) { |
| 32 | + |
| 33 | + // Select pivot position and put all the elements smaller |
| 34 | + // than pivot on left and greater than pivot on right |
| 35 | + int pi = partition(array, low, high); |
| 36 | + |
| 37 | + // Sort the elements on the left of pivot |
| 38 | + quickSort(array, low, pi - 1); |
| 39 | + |
| 40 | + // Sort the elements on the right of pivot |
| 41 | + quickSort(array, pi + 1, high); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + // Driver code |
| 46 | + public static void main(String args[]) { |
| 47 | + int[] data = { 8, 7, 2, 1, 0, 9, 6 }; |
| 48 | + int size = data.length; |
| 49 | + QuickSort qs = new QuickSort(); |
| 50 | + qs.quickSort(data, 0, size - 1); |
| 51 | + System.out.println("Sorted Array in Ascending Order: "); |
| 52 | + System.out.println(Arrays.toString(data)); |
| 53 | + } |
| 54 | +} |
| 55 | +Quicksort Complexity |
| 56 | +Time Complexities |
| 57 | + |
| 58 | + |
0 commit comments