-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy path02 BubbleSort.cpp
48 lines (40 loc) · 921 Bytes
/
02 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
#include <iostream>
using namespace std;
template <class T>
void Print(T& vec, int n, string s){
cout << s << ": [" << flush;
for (int i=0; i<n; i++){
cout << vec[i] << flush;
if (i < n-1){
cout << ", " << flush;
}
}
cout << "]" << endl;
}
void swap(int* x, int* y){
int temp = *x;
*x = *y;
*y = temp;
}
void BubbleSort(int A[], int n){
int flag = 0;
for (int i=0; i<n-1; i++){
for (int j=0; j<n-1-i; j++){
if (A[j] > A[j+1]){
swap(&A[j], &A[j+1]);
flag = 1;
}
}
if (flag == 0){
return;
}
}
}
int main() {
int A[] = {3, 7, 9, 10, 6, 5, 12, 4, 11, 2};
int n = sizeof(A)/sizeof(A[0]);
Print(A, n, "\t\tA");
BubbleSort(A, n);
Print(A, n, " Sorted A");
return 0;
}