tsaiwn@magpie qsort> cat -n myqsort.cpp 1 //myqsort.cpp -- demostration of quick sort, using template function 2 //CopyLeft by tsaiwn@csie.nctu.edu.tw 3 #include 4 template void swap(GG& x, GG& y){ GG t=x; x=y; y=t; } 5 template 6 void myqsort(GG x[], int left, int right) { 7 int i=left, j=right, flag= -1; 8 while(i < j) { 9 if(x[i] > x[j]) { /* 由小到大排 */ 10 swap(x[i], x[j]); 11 //GG t = x[i]; x[i]=x[j]; x[j]=t; /* 或是這樣也可以 */ 12 flag = - flag; 13 } 14 if(flag<0) --j; else i++; 15 } 16 if(left+1 < i) myqsort(x, left, i-1); /* 左邊多於 1 個 */ 17 if(i+1 < right) myqsort(x, i+1, right); /* 右邊多於 1 個 */ 18 } 19 long m[ ] = { 77, 85, 82, 55, 66, 96, 79, 73, 94 }; 20 int nofm = (sizeof(m) / sizeof(long) ); 21 double y[ ] = { 85.5, 94.5, 73.5, 77.5, 66.5, 82.5, 55.5, 96.5, 79.5, 99.5}; 22 int nofy = (sizeof(y) / sizeof(double) ); 23 template 24 void print(YY x[], int n) { 25 cout << x[0]; 26 for(int i=1; i< n; ++i) { 27 if(i%5 == 0 ) cout << endl; /* 5 elements per line */ 28 else cout << ", "; 29 cout << x[i]; 30 } 31 cout << endl; 32 } 33 int main( ) { 34 cout << "Before sort:\n"; print(m, nofm); 35 myqsort(m, 0, nofm-1); 36 cout << "After sort:\n"; 37 print(m, nofm); 38 cout << "------" << endl; 39 cout << "Before sort:\n"; print(y, nofy); 40 myqsort(y, 0, nofy-1); 41 cout << "After sort:\n"; 42 print(y, nofy); 43 } tsaiwn@magpie qsort> g++ myqsort.cpp tsaiwn@magpie qsort> ./a.out Before sort: 77, 85, 82, 55, 66 96, 79, 73, 94 After sort: 55, 66, 73, 77, 79 82, 85, 94, 96 ------ Before sort: 85.5, 94.5, 73.5, 77.5, 66.5 82.5, 55.5, 96.5, 79.5, 99.5 After sort: 55.5, 66.5, 73.5, 77.5, 79.5 82.5, 85.5, 94.5, 96.5, 99.5 tsaiwn@magpie qsort> exit exit Script done on Mon Dec 24 21:58:52 2001