LoganBlackisle

QuickSort

Jun 17th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. package prep_18_sortering;
  2.  
  3. public class QuickSort {
  4. /*
  5. * This function takes last element as pivot, places the pivot element at its
  6. * correct position in sorted array, and places all smaller (smaller than pivot)
  7. * to left of pivot and all greater elements to right of pivot
  8. */
  9. public int partition(int arr[], int low, int high) {
  10. int pivot = arr[high];
  11. int i = (low - 1); // index of smaller element
  12. for (int j = low; j < high; j++) {
  13. // If current element is smaller than or
  14. // equal to pivot
  15. if (arr[j] <= pivot) {
  16. i++;
  17.  
  18. // swap arr[i] and arr[j]
  19. int temp = arr[i];
  20. arr[i] = arr[j];
  21. arr[j] = temp;
  22. }
  23. }
  24.  
  25. // swap arr[i+1] and arr[high] (or pivot)
  26. int temp = arr[i + 1];
  27. arr[i + 1] = arr[high];
  28. arr[high] = temp;
  29.  
  30. return i + 1;
  31. }
  32.  
  33. /*
  34. * The main function that implements QuickSort() arr[] --> Array to be sorted,
  35. * low --> Starting index, high --> Ending index
  36. */
  37. public void sort(int arr[], int low, int high) {
  38. if (low < high) {
  39. /*
  40. * pi is partitioning index, arr[pi] is now at right place
  41. */
  42. int pi = partition(arr, low, high);
  43.  
  44. // Recursively sort elements before
  45. // partition and after partition
  46. sort(arr, low, pi - 1);
  47. sort(arr, pi + 1, high);
  48. }
  49. }
  50.  
  51. /* A utility function to print array of size n */
  52. public static void printArray(int arr[]) {
  53. int n = arr.length;
  54. for (int i = 0; i < n; ++i) {
  55. System.out.print(arr[i] + " ");
  56. }
  57. System.out.println();
  58. }
  59.  
  60. // Driver program
  61. public static void main(String args[]) {
  62. int arr[] = { 10, 7, 8, 9, 1, 5 };
  63. int n = arr.length;
  64.  
  65. QuickSort ob = new QuickSort();
  66. ob.sort(arr, 0, n - 1);
  67.  
  68. System.out.println("sorted array");
  69. printArray(arr);
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment