Advertisement
OnePiece1024

quick sort

Feb 5th, 2020
544
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4.  
  5. // prototype declaration
  6. void quickSort(int* arr, int low, int high);
  7. int _partition(int* arr, int low, int high);
  8.  
  9. // quick sort function
  10. void quickSort(int* arr, int low, int high){
  11.     if(low < high){
  12.         int p = _partition(arr, low, high);
  13.         quickSort(arr, low, p - 1);
  14.         quickSort(arr, p + 1, high);
  15.     }
  16. }
  17.  
  18. // partition function
  19. int _partition(int* arr, int low, int high){
  20.     int pivot = arr[high];
  21.     int i = low;
  22.     for(int j = low; j < high; j++){
  23.         if(arr[j] < pivot){
  24.                 // swap
  25.             int temp = arr[i];
  26.             arr[i++] = arr[j];
  27.             arr[j] = temp;
  28.         }
  29.     }
  30.  
  31.     // swap
  32.     int temp = arr[i];
  33.     arr[i] = arr[high];
  34.     arr[high] = temp;
  35.  
  36.     return i;
  37. }
  38.  
  39. int main()
  40. {
  41.     int arr[5] = {4, 1, 7, -20, 41};
  42.     quickSort(arr, 0, 4);
  43.  
  44.     for(int i = 0; i < 5; i++) printf("%d ", arr[i]);
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement