#include <iostream>
#include <vector>
using namespace std;
void printVector(vector<int> toPrint){
for(int i = 0; i < toPrint.size(); i++){
if (i != 0){
cout << ", ";
}
cout << toPrint[i];
}
cout << endl;
}
int HoarePartition(vector<int> & in){
int startIndex = 0;
int stopIndex = in.size()-1;
int pivot = in[ startIndex ];
cout << "=== Before Partition ===" <<endl;
printVector(in);
while (true){
while ( in[ startIndex ] <= pivot ){
startIndex++;
}
while ( in[ stopIndex ] > pivot ){
stopIndex--;
}
if( startIndex < stopIndex ){
// swap!
int swapCup = in[ startIndex ];
in[ startIndex ] = in[ stopIndex ];
in[ stopIndex ] = swapCup;
}
else{
cout << "=== After Partition ===" << endl;
printVector(in);
return stopIndex;
}
}
}
int main() {
vector<int> test;
test.push_back(5);
test.push_back(9);
test.push_back(8);
test.push_back(4);
test.push_back(1);
test.push_back(2);
HoarePartition(test);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdm9pZCBwcmludFZlY3Rvcih2ZWN0b3I8aW50PiB0b1ByaW50KXsKCWZvcihpbnQgaSA9IDA7IGkgPCB0b1ByaW50LnNpemUoKTsgaSsrKXsKCQlpZiAoaSAhPSAwKXsKCQkJY291dCA8PCAiLCAiOwoJCX0KCQljb3V0IDw8IHRvUHJpbnRbaV07Cgl9Cgljb3V0IDw8IGVuZGw7Cn0KCgppbnQgSG9hcmVQYXJ0aXRpb24odmVjdG9yPGludD4gJiBpbil7CglpbnQgc3RhcnRJbmRleCA9IDA7IAoJaW50IHN0b3BJbmRleCA9IGluLnNpemUoKS0xOwoJaW50IHBpdm90ID0gaW5bIHN0YXJ0SW5kZXggXTsKCgljb3V0IDw8ICI9PT0gQmVmb3JlIFBhcnRpdGlvbiA9PT0iIDw8ZW5kbDsKCXByaW50VmVjdG9yKGluKTsKCgl3aGlsZSAodHJ1ZSl7CgkJd2hpbGUgKCBpblsgc3RhcnRJbmRleCBdIDw9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