Skip to content

Instantly share code, notes, and snippets.

@rcanepa
Created February 19, 2015 16:49
Show Gist options
  • Save rcanepa/767040cb76491463287d to your computer and use it in GitHub Desktop.
Save rcanepa/767040cb76491463287d to your computer and use it in GitHub Desktop.
c++ Quick Sort (random pivot)
#include <iostream>
#include <stdlib.h>
void quick_sort(int *list, int p, int r);
int main(int argc, char const *argv[])
{
int n = 11;
int list[n];
srand(time(NULL));
std::cout << "Before sorting." << std::endl;
for (int i = 0; i < n; i++)
{
list[i] = rand() % 300;
std::cout << list[i] << ", ";
}
std::cout << std::endl;
int pivot_key = rand() % n;
int pivot = list[pivot_key];
list[pivot_key] = list[n - 1];
list[n - 1] = pivot;
std::cout << "Before sorting. After changing the pivot." << std::endl;
for (int i = 0; i < n; i++)
{
std::cout << list[i] << ", ";
}
std::cout << std::endl;
quick_sort(list, 0, n - 1);
std::cout << "After sorting." << std::endl;
for (int j = 0; j < n; j++)
{
std::cout << list[j] << ", ";
}
std::cout << std::endl;
return 0;
}
void quick_sort(int *list, int p, int r)
{
if (p < r)
{
int q = p;
int temp_key;
for (int u = p; u < r; ++u)
{
if (list[u] <= list[r])
{
temp_key = list[q];
list[q] = list[u];
list[u] = temp_key;
q++;
}
}
temp_key = list[q];
list[q] = list[r];
list[r] = temp_key;
quick_sort(list, p, q - 1);
quick_sort(list, q + 1, r);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment