-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.h
More file actions
37 lines (36 loc) · 1.48 KB
/
bubble_sort.h
File metadata and controls
37 lines (36 loc) · 1.48 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
#include <iostream>
#include <cstdint>
template<typename T>
void bubble_sort(T* data, size_t num)
{
std::cout << "choose bubble sort ." << std::endl;
// 每次循环,让 [current_loop_len] 变成本次循环的最大值
for (size_t current_loop_len = num - 1; current_loop_len > 0; current_loop_len--) {
#ifdef DEBUG
std::cout << "-------------- loop time " << (num - current_loop_len) << " start "
<< "---------------" << std::endl;
#endif
for (size_t current_index = 0; current_index < current_loop_len; current_index++) {
T* current_data = data + current_index;
T* bigger_data = data + current_index + 1;
#ifdef DEBUG
std::cout << *current_data << " - " << *bigger_data << " change to ";
#endif
if (*current_data > *bigger_data) {
T temp = *current_data;
*current_data = *bigger_data;
*bigger_data = temp;
}
#ifdef DEBUG
std::cout << *current_data << " - " << *bigger_data << std::endl;
#endif
}
#ifdef DEBUG
std::cout << "-------------- loop time " << (num - current_loop_len) << " result "
<< "--------------" << std::endl;
show_data(data, num);
std::cout << "-------------- loop time " << (num - current_loop_len) << " end "
<< "-----------------" << std::endl << std::endl;
#endif
}
}