#include <iostream>
using namespace std;
bool bubble2(int *a,int lo, int hi){
bool sorted = true;
while (++lo<hi)
if (a[lo - 1]>a[lo]){
sorted = false;
swap(a[lo - 1], a[lo]);
}
return sorted;
}
void bubblesort2(int *a,int lo, int hi){
while (!bubble2(a,lo,hi--));
}
void bubblesort1(int *a, int lo, int hi){
for (int i = lo; i < hi-1;i++)
for (int j = lo; j < hi - 1 - i; j++){
if (a[j]>a[j + 1])
swap(a[j], a[j + 1]);
}
}
int bubble3(int *a, int lo, int hi){
int sorted = lo;
while (++lo<hi)
if (a[lo - 1]>a[lo]){
sorted = lo;
swap(a[lo - 1], a[lo]);
}
return sorted;
}
void bubblesort3(int *a, int lo, int hi){
while (lo<(hi=bubble3(a,lo,hi)));
}
int main(){
int a[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
bubblesort1(a, 0, 10);//未优化的冒泡算法
//bubblesort2(a, 0, 10);//如果循环至某一行,如果无序对为0,则可以跳过无效循环
//bubblesort3(a, 0, 10);//如果循环至某一行,某前缀的后缀皆有序则可以只排序前缀,从而减少循环次数
for (int i = 0; i < 10; i++)
cout << a[i] << endl;
return 0;
}
bubblesort的改进
最新推荐文章于 2024-01-16 05:15:00 发布