Quick Sort Algorithm

mail@pastecode.io avatar
unknown
c_cpp
11 days ago
948 B
3
Indexable
Never
#include <iostream>

using namespace std;

int partition(int my_array[], int low, int high) {
    int pivot = my_array[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (my_array[j] <= pivot) {
            i++;
            swap(my_array[i], my_array[j]);
        }
    }
    swap(my_array[i + 1], my_array[high]);
    return i + 1;
}

void quickSort(int my_array[], int low, int high) {
    if (low < high) {
        int pivot_index = partition(my_array, low, high);
        quickSort(my_array, low, pivot_index - 1);
        quickSort(my_array, pivot_index + 1, high);
    }
}

int main() {
    int my_array[] = {64, 34, 25, 12, 22, 11, 90, 5};
    int size = sizeof(my_array) / sizeof(my_array[0]);
    quickSort(my_array, 0, size - 1);
    
    // Print sorted array
    for (int i = 0; i < size; i++) {
        cout << my_array[i] << " ";
    }
    cout << endl;

    return 0;
}
Leave a Comment