Skip to content

Commit 609975e

Browse files
authored
Update bubble_sort.h
Bubble sort using template and funtion @pierredavidbelanger @Samana @blackball @wycg1984
1 parent 2ac19a7 commit 609975e

File tree

1 file changed

+44
-23
lines changed

1 file changed

+44
-23
lines changed

include/bubble_sort.h

Lines changed: 44 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,29 +23,50 @@
2323
#ifndef _BUBBLE_SORT_H_
2424
#define _BUBBLE_SORT_H_
2525

26-
#include <assert.h>
27-
#include <generic.h>
28-
29-
namespace alg {
30-
template<typename T>
31-
static void BubbleSort(T list[], int start, int end){
32-
int i;
33-
bool swapped;
34-
35-
assert(start < end);
36-
37-
do {
38-
swapped = false;
39-
for(i = start+1; i <= end; i++) {
40-
if(list[i-1] > list[i]) {
41-
// swap them and remember something changed
42-
swap(list[i-1], list[i]);
43-
swapped = true;
44-
}
45-
}
46-
} while(swapped);
47-
}
26+
#include <bits/stdc++>
27+
using namespace std;
28+
29+
template <class X> void bubble(X *items,int count)
30+
{
31+
X t;
32+
33+
for(int a=1; a<count; a++)
34+
for(int b=count-1; b>=a; b--)
35+
if(items[b-1] > items[b]) {
36+
t = items[b-1];
37+
items[b-1] = items[b];
38+
items[b] = t;
39+
}
4840
}
4941

42+
int main()
43+
{
44+
int iarray[7] = {7, 5, 4, 3, 9, 8, 6};
45+
double darray[5] = {4.3, 2.5, -0.9, 10.2, 3.0};
46+
47+
cout << "Here is unsorted integer array: ";
48+
for(int i=0; i<7; i++)
49+
cout << iarray[i] << ' ';
50+
cout << endl;
51+
52+
bubble(iarray, 7);
53+
54+
cout << "Here is sorted integer array: ";
55+
for(int i=0; i<7; i++)
56+
cout << iarray[i] << ' ';
57+
cout << endl;
5058

51-
#endif // _BUBBLE_SORT_H_
59+
cout << "Here is unsorted double array: ";
60+
for(int i=0; i<5; i++)
61+
cout << darray[i] << ' ';
62+
cout << endl;
63+
64+
bubble(darray, 5);
65+
66+
cout << "Here is sorted double array: ";
67+
for(int i=0; i<5; i++)
68+
cout << darray[i] << ' ';
69+
cout << endl;
70+
71+
return 0;
72+
}

0 commit comments

Comments
 (0)