Maruf_Hasan

Quicksort

Sep 3rd, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. /* C++ implementation of QuickSort */
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // A utility function to swap two elements
  6. void swap(int* a, int* b)
  7. {
  8. int t = *a;
  9. *a = *b;
  10. *b = t;
  11. }
  12.  
  13. /* This function takes last element as pivot, places
  14. the pivot element at its correct position in sorted
  15. array, and places all smaller (smaller than pivot)
  16. to left of pivot and all greater elements to right
  17. of pivot */
  18. int partition (int arr[], int low, int high)
  19. {
  20. int pivot = arr[high]; // pivot
  21. int i = (low - 1); // Index of smaller element
  22.  
  23. for (int j = low; j <= high - 1; j++)
  24. {
  25. // If current element is smaller than the pivot
  26. if (arr[j] < pivot)
  27. {
  28. i++; // increment index of smaller element
  29. swap(&arr[i], &arr[j]);
  30. }
  31. }
  32. swap(&arr[i + 1], &arr[high]);
  33. return (i + 1);
  34. }
  35.  
  36. /* The main function that implements QuickSort
  37. arr[] --> Array to be sorted,
  38. low --> Starting index,
  39. high --> Ending index */
  40. void quickSort(int arr[], int low, int high)
  41. {
  42. if (low < high)
  43. {
  44. /* pi is partitioning index, arr[p] is now
  45. at right place */
  46. int pi = partition(arr, low, high);
  47.  
  48. // Separately sort elements before
  49. // partition and after partition
  50. quickSort(arr, low, pi - 1);
  51. quickSort(arr, pi + 1, high);
  52. }
  53. }
  54.  
  55. /* Function to print an array */
  56. void printArray(int arr[], int size)
  57. {
  58. int i;
  59. for (i = 0; i < size; i++)
  60. cout << arr[i] << " ";
  61. cout << endl;
  62. }
  63.  
  64. // Driver Code
  65. int main()
  66. {
  67. int arr[] = {10, 7, 8, 9, 1, 5};
  68. int n = sizeof(arr) / sizeof(arr[0]);
  69. quickSort(arr, 0, n - 1);
  70. cout << "Sorted array: \n";
  71. printArray(arr, n);
  72. return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment