QuickSort.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // https://www.geeksforgeeks.org/quick-sort-algorithm/
  2. import java.util.Arrays;
  3. class QuickSort {
  4. // Partition function
  5. static int partition(int[] arr, int low, int high) {
  6. // Choose the pivot
  7. int pivot = arr[high];
  8. // Index of smaller element and indicates
  9. // the right position of pivot found so far
  10. int i = low - 1;
  11. // Traverse arr[low..high] and move all smaller
  12. // elements to the left side. Elements from low to
  13. // i are smaller after every iteration
  14. for (int j = low; j <= high - 1; j++) {
  15. if (arr[j] < pivot) {
  16. i++;
  17. swap(arr, i, j);
  18. }
  19. }
  20. // Move pivot after smaller elements and
  21. // return its position
  22. swap(arr, i + 1, high);
  23. return i + 1;
  24. }
  25. // Swap function
  26. static void swap(int[] arr, int i, int j) {
  27. int temp = arr[i];
  28. arr[i] = arr[j];
  29. arr[j] = temp;
  30. }
  31. // The QuickSort function implementation
  32. static void quickSort(int[] arr, int low, int high) {
  33. if (low < high) {
  34. // pi is the partition return index of pivot
  35. int pi = partition(arr, low, high);
  36. // Recursion calls for smaller elements
  37. // and greater or equals elements
  38. quickSort(arr, low, pi - 1);
  39. quickSort(arr, pi + 1, high);
  40. }
  41. }
  42. public static void main(String[] args) {
  43. int[] arr = {10, 7, 8, 9, 1, 5};
  44. int n = arr.length;
  45. quickSort(arr, 0, n - 1);
  46. for (int val : arr) {
  47. System.out.print(val + " ");
  48. }
  49. }
  50. }