-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
bubble_sort.h
51 lines (44 loc) · 1.52 KB
/
bubble_sort.h
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
/*******************************************************************************
* ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* BUBBLE SORT
*
* Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple
* sorting algorithm that works by repeatedly stepping through the list to be
* sorted, comparing each pair of adjacent items and swapping them if they are
* in the wrong order. The pass through the list is repeated until no swaps are
* needed, which indicates that the list is sorted. The algorithm gets its name
* from the way smaller elements "bubble" to the top of the list. Because it
* only uses comparisons to operate on elements, it is a comparison sort.
* Although the algorithm is simple, most of the other sorting algorithms are
* more efficient for large lists.
*
* http://en.wikipedia.org/wiki/Bubble_sort
******************************************************************************/
#ifndef _BUBBLE_SORT_H_
#define _BUBBLE_SORT_H_
#include <assert.h>
#include <generic.h>
namespace alg {
template<typename T>
static void BubbleSort(T list[], int start, int end){
int i;
bool swapped;
assert(start < end);
do {
swapped = false;
for(i = start+1; i <= end; i++) {
if(list[i-1] > list[i]) {
// swap them and remember something changed
swap(list[i-1], list[i]);
swapped = true;
}
}
} while(swapped);
}
}
#endif // _BUBBLE_SORT_H_