5.QuickSort - C++

less than 1 minute read

5.QuickSort - C++




#include <iostream>

void swap(int *a, int *b) {
    int t = *a;
    *a = *b;
    *b = t;
}
 
void quickSort(int left, int right, int *arr) {
    int pivot = arr[left];
    int less = left;
    int more = right+1;
     
    if (left < right) {
        do {
            do
                less++;
            while (less <= right && arr[less] < pivot);
 
            do
                more--;
            while (more >= left && arr[more] > pivot);
 
            if (less < more)
                swap(&arr[less], &arr[more]);
 
        } while (less < more);
        swap(&arr[left], &arr[more]);
         
        quickSort(left, more - 1,arr);
        quickSort(more + 1, right, arr);
    }
 
}

int main(int argc, const char * argv[]) {
    int arr[] = { 3,2,3,1,5,6,7,8,9,10 };
    int size = sizeof(arr)/sizeof(int);
    
    quickSort(0, size, arr);
    
    for(int x:arr) std::cout << x << " ";
    
}








Leave a comment