最近其实写了一些别的博客不太好发出来,因为不确定是否写得准确,所以就靠这个水水啦~~
递归写法:
#include<bits/stdc++.h>
using namespace std;
void disp(int a[], int n) {
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
void BubbleSort(int a[],int n,int i) {
bool exchange = false;
if (i == n - 1)return;
else {
for (int j = n - 1; j > i; j--) {
if (a[j] < a[j - 1]) {
swap(a[j], a[j - 1]);
exchange = true;
}
}
if (exchange)
BubbleSort(a, n, i + 1);
else
return;
}
}
int main() {
int n = 10;
int a[] = { 0,5,2,7,8,3,9,4,6,1 };
cout << "排序前序列:";
disp(a, n);
BubbleSort(a, n, 0);
cout << "排序后序列:";
disp(a, n);
}
非递归写法(有参考别人的进行改良):
#include<bits/stdc++.h>
using namespace std;
void disp(int a[], int n) {
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
void BubbleSort(int a[], int n) {
int sortBorder = n - 1;
for (int i = 0; i < n - 1; i++) {
bool exchange = false;
int lastExchangeIndex = 0;
for (int j = 0; j < sortBorder; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
lastExchangeIndex =j;
exchange = true;
}
}
if (!exchange)
return;
sortBorder = lastExchangeIndex;
}
}
int main() {
int n = 10;
int a[] = { 0,5,2,7,8,3,9,4,6,1 };
cout << "排序前序列:";
disp(a, n);
BubbleSort(a, n);
cout << "排序后序列:";
disp(a, n);
}
简单记录一下课上写的代码...