Skip to content

Instantly share code, notes, and snippets.

@makersm
Last active January 11, 2018 07:14
Show Gist options
  • Save makersm/c91ae497b07d4f1af5d0ed9a6fd60588 to your computer and use it in GitHub Desktop.
Save makersm/c91ae497b07d4f1af5d0ed9a6fd60588 to your computer and use it in GitHub Desktop.
quick sort
#include <iostream>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <map>
#define MAX 20
using namespace std;
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
// partition
while (i <= j) {
while (arr[i] < pivot)
i++;
while (pivot < arr[j])
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
// recursion
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
void printArray(int arr[], int length) {
for(int i = 0; i < length; i++){
cout<< arr[i] << " ";
}
cout<< endl;
}
int main() {
// init
int arr[MAX];
srand(time(NULL));
for(int i = 0; i < MAX; i++){
arr[i] = rand() % 20 + 1;
}
cout<<"before quickSorting: ";
printArray(arr, MAX);
quickSort(arr, 0, MAX-1);
cout<<"after quickSorting: ";
printArray(arr, MAX);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment