-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.C
More file actions
64 lines (49 loc) · 1.31 KB
/
BubbleSort.C
File metadata and controls
64 lines (49 loc) · 1.31 KB
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
#include <stdlib.h> /* srand, rand */
void BubbleSort(){
const int arraysize=1000;
int arrayunsorted[arraysize];
for (int i=0;i<arraysize;i++){
arrayunsorted[i]=rand()%arraysize;
}
int swappedcounts=arraysize;
while (swappedcounts>0){
swappedcounts=0;
for (int i=0;i<arraysize;i++){
int a=arrayunsorted[i];
int b=arrayunsorted[i+1];
if(a>b) {arrayunsorted[i]=b; arrayunsorted[i+1]=a; swappedcounts++;}
}//end sorting loop
}// end of while
for (int i=0;i<arraysize;i++){
cout<<arrayunsorted[i]<<endl;
}
} //end of code
// is clearly a O(n2) algorithm :).
/*
#include <stdlib.h>
void BubbleSort(){
const int arraysize=1000;
int arrayunsorted[arraysize];
for (int i=0;i<arraysize;i++){
arrayunsorted[i]=rand()%arraysize;
}
bool flag=true;
while (flag){
flag=false;
for (int i=0;i<arraysize;i++){
int a=arrayunsorted[i];
int b=arrayunsorted[i+1];
if(a>b) {arrayunsorted[i]=b; arrayunsorted[i+1]=a;}
}//end sorting loop
for (int i=0;i<arraysize;i++){
int a=arrayunsorted[i];
int b=arrayunsorted[i+1];
if(a>b) {flag=true;}
}//end checking loop
}// end of while
for (int i=0;i<arraysize;i++){
cout<<arrayunsorted[i]<<endl;
}
} //end of code
// is clearly a O(n2) algorithm :).
*/