Advertisement
AaronThomsen

QuickSort

May 10th, 2018
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. using namespace std;
  5.  
  6. void quickSort(int arr[], int size);
  7. void quickSort(int arr[], int leftIndex, int rightIndex);
  8. int quickSortPartition(int arr[], int leftIndex, int rightIndex);
  9.  
  10. int main(){
  11.     int arr[10] = {15, 6, 8, -1, 0, 23, 1, 42, 32, 44};
  12.  
  13.     quickSort(arr, 10);
  14.  
  15.     for(auto i : arr)
  16.         cout << i << " ";
  17. }
  18.  
  19. void quickSort(int arr[], int size){
  20.     quickSort(arr, 0, size - 1);
  21. }
  22.  
  23. void quickSort(int arr[], int leftIndex, int rightIndex){
  24.     if(leftIndex < rightIndex){
  25.         int partitionIndex = quickSortPartition(arr, leftIndex, rightIndex);
  26.  
  27.         quickSort(arr, leftIndex, partitionIndex - 1);
  28.         quickSort(arr, partitionIndex + 1, rightIndex);
  29.     }
  30. }
  31.  
  32. int quickSortPartition(int arr[], int leftIndex, int rightIndex){
  33.     int p = arr[rightIndex];
  34.     int smallIndex = leftIndex;
  35.  
  36.     for(int i = leftIndex; i < rightIndex; i++){
  37.         if(arr[i] < p){
  38.             swap(arr[smallIndex++], arr[i]);
  39.         }
  40.     }
  41.  
  42.     swap(arr[smallIndex], arr[rightIndex]);
  43.     return smallIndex;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement