
程序代码:
1 //bccn.cpp
2 #include <iostream>
3 #include <algorithm>
4 #include <iterator>
5 #include <fstream>
6 #include <vector>
7 using namespace std;
8
9 void swap(int &a, int &b)
10 {
11 a += b;
12 b = a - b;
13 a = a - b;
14 }
15
16 void qsort(vector<int> &ivec, size_t low, size_t high)
17 {//保证参数的合法性
18 if (low >= high)
19 {
20 return;
21 }
22
23 size_t i = low, j = high;
24 size_t comp = ivec[low];
25
26 while (i<j)
27 {
28 while (i<j && comp<ivec[j])
29 {//找到第一小于的数
30 --j;
31 }
32 if (i < j)
33 {
34 swap(ivec[i], ivec[j]);
35 ++i;
36 }
37 while (i<j && comp>ivec[i])
38 {//找到第一大于的数
39 ++i;
40 }
41 if (i < j)
42 {
43 swap(ivec[i], ivec[j]);
44 --j;
45 }
46 }
47 qsort(ivec, low, i?i-1:min(i-1, low));
48 qsort(ivec, i+1, high);
49 }
50
51 int main(int argc, char **argv)
52 {
53 if (2 != argc)
54 {
55 cout << string("argc != 2") << endl;
56 return -1;
57 }
58
59 ifstream fin(argv[1]);
60 istream_iterator<int> beg(fin), end;
61 ostream_iterator<int> out(cout, " ");
62 vector<int> ivec;
63
64 while (beg != end)
65 {
66 ivec.push_back(*beg);
67 ++beg;
68 }
69 cout << string("before sort:");
70 copy(ivec.begin(), ivec.end(), out);
71 cout << endl << string("after sort:");
72 // sort(ivec.begin(), ivec.end());
73 qsort(ivec, 0, ivec.size()-1);
74 copy(ivec.begin(), ivec.end(), out);
75 cout << endl;
76
77 return 0;
78 }