Advertisement
shawonrog

QUICKSORT C PLUS PLUS

Aug 3rd, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. // Function to swap numbers
  6. void swap(int *a, int *b){
  7.     int temp = *a;
  8.     *a = *b;
  9.     *b = temp;
  10. }
  11.  
  12. /* This function takes last element as pivot,
  13.    places the pivot element at its correct
  14.    position in sorted  array, and places
  15.    all smaller (smaller than pivot) to left
  16.    of pivot and all greater elements to
  17.    right of pivot */
  18. int partition (int arr[], int l, int h)
  19. {
  20.     int x = arr[h];
  21.     int i = (l - 1);
  22.  
  23.     for (int j = l; j <= h- 1; j++)
  24.     {
  25.         if (arr[j] <= x)
  26.         {
  27.             i++;
  28.             swap (&arr[i], &arr[j]);
  29.         }
  30.     }
  31.     swap (&arr[i + 1], &arr[h]);
  32.     return (i + 1);
  33. }
  34.  
  35. /* A[] --> Array to be sorted,
  36. l --> Starting index,
  37. h --> Ending index */
  38. void quickSort(int A[], int l, int h)
  39. {
  40.     if (l < h)
  41.     {
  42.         /* Partitioning index */
  43.         int p = partition(A, l, h);
  44.         quickSort(A, l, p - 1);
  45.         quickSort(A, p + 1, h);
  46.     }
  47.  
  48. }
  49.  
  50. // Driver code
  51. int main(){
  52.  
  53.     int n = 5;
  54.     int arr[n] = {4, 2, 6, 9, 2};
  55.  
  56.     quickSort(arr, 0, n-1);
  57.  
  58.         for(int i = 0; i < n; i++){
  59.             printf("%d ",arr[i]);
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement