-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSort.h
54 lines (43 loc) · 1.63 KB
/
BubbleSort.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
52
53
54
/*
Author: naiyong, aonaiyong@gmail.com
Date: Oct 14, 2014
Problem: Bubble Sort
Difficulty: 2
Source: http://en.wikipedia.org/wiki/Bubble_sort
Notes:
Sort an array using bubble sort.
Solution: http://en.wikipedia.org/wiki/Bubble_sort
http://www.sorting-algorithms.com/bubble-sort
Loop Invariant: | | < | < |
0 i-1 i n N
| | < |
0 n N
A[n], ..., A[N] are in their final, sorted positions (N = A.size - 1).
The last swap of current pass happened at index i.
Termination: | < |
n N
Worst-case time: O(n^2) comparisons/swaps.
Best-case time: O(n) comparisons, O(1) swaps.
Average-case time: O(n^2) comparisons/swaps.
Worst-case space: O(1).
Property: Stable & In-place & Adaptive.
*/
#ifndef BUBBLESORT_H_
#define BUBBLESORT_H_
#include <utility>
using std::swap;
class Solution {
public:
void bubbleSort(int A[], int n) {
while (n > 0) {
int newn = 0;
for (int i = 1; i < n; ++i)
if (A[i-1] > A[i]) {
swap(A[i-1], A[i]);
newn = i;
}
n = newn;
}
}
};
#endif /* BUBBLESORT_H_ */