Skip to content

Instantly share code, notes, and snippets.

@siddhantkushwaha
Last active August 14, 2019 16:05
Show Gist options
  • Save siddhantkushwaha/5e45bce2ee079f34d105fc2c85ec45a6 to your computer and use it in GitHub Desktop.
Save siddhantkushwaha/5e45bce2ee079f34d105fc2c85ec45a6 to your computer and use it in GitHub Desktop.
Most partitioning implementations depend on where the pivot is, but not this one.
#include "bits/stdc++.h"
using namespace std;
int partition(int a[], int low, int high) {
/* try with different values of p in range [low, high] */
int p = (low + high) / 2;
int i = low;
int j = high;
while (1) {
while (a[i] <= a[p] && i != p)
i++;
while (a[j] > a[p])
j--;
if (i < j) {
if (i == p)
p = j;
else if (j == p)
p = i;
swap(a[i], a[j]);
} else
return p;
}
}
int main() {
int a[] = {1, 234, 43, 24, 2, 46, 426, 456, 97, 64, 2, 93, 24};
int n = sizeof(a) / 4;
partition(a, 0, n - 1);
for (int i = 0; i <= n - 1; i++)
cout << a[i] << " ";
cout << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment