-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathbubblesort.cpp
69 lines (55 loc) · 1.21 KB
/
bubblesort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/* 简单版本 */
void bubblesort( vector<int> & vec )
{
for ( int i = 0; i < vec.size() - 1; i++ )
{
for ( int j = 0; j < vec.size() - i - 1; j++ )
{
if ( vec[j] > vec[j + 1] )
{
swap( vec[j], vec[j + 1] );
}
}
}
}
/* 改进版本 */
void bubblesort1( vector<int> & vec )
{
for ( int i = 0; i < vec.size() - 1; i++ )
{
bool exchange = false;
for ( int j = 0; j < vec.size() - i - 1; j++ )
{
if ( vec[j] > vec[j + 1] )
{
swap( vec[j], vec[j + 1] );
exchange = true;
}
}
if ( !exchange )
{
break;
}
}
}
void printvec( const vector<int> & vec, const string & strbegin = "", const string & strend = "" )
{
cout << strbegin << endl;
for ( auto val : vec )
{
cout << val << "\t";
}
cout << endl;
cout << strend << endl;
}
int main( void )
{
vector<int> vec = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
printvec( vec );
bubblesort1( vec );
printvec( vec, "after sort", "" );
}