Last active
August 29, 2015 14:07
-
-
Save 910JQK/4077b3c72cf16d6f59fa to your computer and use it in GitHub Desktop.
Quick Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "qsort.hpp" | |
using std::cin; | |
using std::cout; | |
const int maxn = 100; | |
struct Vector { | |
int x; | |
int y; | |
bool operator< (const Vector &p2){ | |
Vector &p1 = *this; | |
return ((p1.x*p1.x+p1.y*p1.y) < (p2.x*p2.x+p2.y*p2.y)); | |
} | |
friend std::ostream& operator<< (std::ostream &left, const Vector &right){ | |
left << "(" << right.x << ", " << right.y << ")"; | |
} | |
}; | |
bool compare(const Vector &p1, const Vector &p2){ | |
return (p1.y < p2.y); | |
} | |
int main(int argc, char *argv[]){ | |
Vector data[maxn]; | |
int i = 0; | |
while(!cin.eof() && i < maxn && cin >> data[i].x >> data[i].y){ | |
i++; | |
} | |
int count = i; | |
qsort(data, data+count-1, compare); | |
for(i=0; i<count; i++){ | |
cout << data[i]; | |
} | |
cout << '\n'; | |
qsort(data, data+count-1); | |
for(i=0; i<count; i++){ | |
cout << data[i]; | |
} | |
cout << '\n'; | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <class Type> | |
void qsort(Type *head, Type *tail, bool (*compare)(const Type &, const Type &) = NULL){ | |
//std::cout << "sort:" << *head << " " << *tail << '\n'; | |
Type *middle = (head + (tail-head)/2); | |
Type *left = head; | |
Type *right = head; | |
Type pivot = *middle; | |
Type temp = *tail; | |
*tail = pivot; | |
*middle = temp; | |
while(left < tail){ | |
if(compare? compare(*left, pivot): *left < pivot){ | |
temp = *right; | |
*right = *left; | |
*left = temp; | |
right++; | |
} | |
left++; | |
} | |
temp = *tail; | |
*tail = *right; | |
*right = temp; | |
if(right+1 < tail) | |
qsort(right+1, tail, compare); | |
if(head < right-1) | |
qsort(head, right-1, compare); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment