|
| 1 | +/** |
| 2 | + * Class for InsertionSort implementation |
| 3 | + * |
| 4 | + * Created by Amar Veerepalli |
| 5 | + */ |
| 6 | +package com.deepak.algorithms.Sorting; |
| 7 | + |
| 8 | +import java.util.Arrays; |
| 9 | + |
| 10 | + |
| 11 | +public class QuickSort { |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + int[] valuesToBeSorted = {7, 10, 47, 40, 83, 84, 65, 61, 32, 55, 49, 46, 25, 20, 93, 63, 54, 10}; |
| 15 | + quickSort(valuesToBeSorted, 0, valuesToBeSorted.length - 1); |
| 16 | + Arrays.stream(valuesToBeSorted).forEach(n -> System.out.print(n + ",")); |
| 17 | + |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Quicksort is a divide and conquer algorithm. |
| 22 | + * It first divides a large list into two smaller sub-lists and then recursively sort the two sub-lists. |
| 23 | + * If we want to sort an array without any extra space, quicksort is a good option. On average, time complexity is O(n log(n)). |
| 24 | + * <p> |
| 25 | + * The basic step of sorting an array are as follows: |
| 26 | + * <p> |
| 27 | + * Select a pivot, normally the middle one |
| 28 | + * From both ends, swap elements and make left elements < pivot and all right > pivot |
| 29 | + * Recursively sort left part and right part |
| 30 | + */ |
| 31 | + private static void quickSort(int[] numbers, int low, int high) { |
| 32 | + int middle = low + (high - low) / 2; |
| 33 | + int pivot = numbers[middle]; |
| 34 | + |
| 35 | + // make left < pivot and right > pivot |
| 36 | + int i = low, j = high; |
| 37 | + while (i < j) { |
| 38 | + // If the current value from the left list is smaller then the pivot, then get the next element from the left list |
| 39 | + while (numbers[i] < pivot) { |
| 40 | + i++; |
| 41 | + } |
| 42 | + |
| 43 | + // If the current value from the right list is larger then the pivot, then get the next element from the right list |
| 44 | + while (numbers[j] > pivot) { |
| 45 | + j--; |
| 46 | + } |
| 47 | + |
| 48 | + // If we have found a values in the left list which is larger then |
| 49 | + // the pivot element and if we have found a value in the right list |
| 50 | + // which is smaller then the pivot element then we exchange the |
| 51 | + // values. |
| 52 | + // As we are done we can increase i and j |
| 53 | + if (i <= j) { |
| 54 | + int temp = numbers[j]; |
| 55 | + numbers[j] = numbers[i]; |
| 56 | + numbers[i] = temp; |
| 57 | + i++; |
| 58 | + j--; |
| 59 | + } |
| 60 | + if (low < j) |
| 61 | + quickSort(numbers, low, j); |
| 62 | + |
| 63 | + if (high > i) |
| 64 | + quickSort(numbers, i, high); |
| 65 | + |
| 66 | + |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments