Skip to content

Commit 567383e

Browse files
authored
feat: update bubble sort algorithm (doocs#827)
1 parent 8dcceb9 commit 567383e

File tree

3 files changed

+44
-110
lines changed

3 files changed

+44
-110
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
7+
void bubbleSort(vector<int>& arr)
8+
{
9+
int n = arr.size();
10+
for (int i = 0; i < n - 1; ++i)
11+
{
12+
bool change = false;
13+
for (int j = 0; j < n - i - 1; ++j)
14+
{
15+
if (arr[j] > arr[j + 1])
16+
{
17+
swap(arr[j], arr[j + 1]);
18+
change = true;
19+
}
20+
}
21+
if (!change) break;
22+
}
23+
}
24+
25+
int main()
26+
{
27+
vector<int> arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
28+
bubbleSort(arr);
29+
for (int v : arr) cout << v << " ";
30+
cout << endl;
31+
}

basic/sorting/BubbleSort/README.md

+13-46
Original file line numberDiff line numberDiff line change
@@ -101,67 +101,34 @@ func main() {
101101
```cpp
102102
#include <iostream>
103103
#include <vector>
104-
#include <string>
105104

106105
using namespace std;
107106

108-
/* 简单版本 */
109-
void bubblesort(vector<int> &vec)
110-
{
111-
for (int i = 0; i < vec.size() - 1; i++)
112-
{
113-
for (int j = 0; j < vec.size() - i - 1; j++)
114-
{
115-
if (vec[j] > vec[j + 1])
116-
{
117-
swap(vec[j], vec[j + 1]);
118-
}
119-
}
120-
}
121-
}
122107

123-
/* 改进版本 */
124-
void bubblesort1(vector<int> &vec)
108+
void bubbleSort(vector<int>& arr)
125109
{
126-
for (int i = 0; i < vec.size() - 1; i++)
110+
int n = arr.size();
111+
for (int i = 0; i < n - 1; ++i)
127112
{
128-
bool exchange = false;
129-
for (int j = 0; j < vec.size() - i - 1; j++)
113+
bool change = false;
114+
for (int j = 0; j < n - i - 1; ++j)
130115
{
131-
if (vec[j] > vec[j + 1])
116+
if (arr[j] > arr[j + 1])
132117
{
133-
swap(vec[j], vec[j + 1]);
134-
exchange = true;
118+
swap(arr[j], arr[j + 1]);
119+
change = true;
135120
}
136121
}
137-
138-
if (!exchange)
139-
{
140-
break;
141-
}
122+
if (!change) break;
142123
}
143124
}
144125

145-
void printvec(const vector<int> &vec, const string &strbegin = "", const string &strend = "")
126+
int main()
146127
{
147-
cout << strbegin << endl;
148-
for (auto val : vec)
149-
{
150-
cout << val << "\t";
151-
}
152-
128+
vector<int> arr = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
129+
bubbleSort(arr);
130+
for (int v : arr) cout << v << " ";
153131
cout << endl;
154-
cout << strend << endl;
155-
}
156-
157-
int main(void)
158-
{
159-
vector<int> vec = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
160-
printvec(vec);
161-
162-
bubblesort1(vec);
163-
164-
printvec(vec, "after sort", "");
165132
}
166133
```
167134

basic/sorting/BubbleSort/bubblesort.cpp

-64
This file was deleted.

0 commit comments

Comments
 (0)