每趟结束时,不仅能挤出一个最大值到最后面位置,还能同时部分理顺其他元素;
**一旦下趟没有交换,还可提前结束排序**
c++代码实现
// 原始冒泡排序
void bubblf_sort(SqList &L){
// 从大到小有序
for(i = 1; i <= L.length; ++i)
for(j = 1; j <= L.length - 1; j++){
if(L.r[j + 1].key < L.r[j].key){
temp = L.r[j + 1];
L.r[j + 1] = L.r[j];
L.r[j] = temp;
}
}
}
// 改进后的算法
void bubblf_sort(SqList &L){
for(i = 1, change = true; i <= L.length - 1 && change; i++){
change = false;
for(j = 1; j < L.length - i; ++i)
if(L.r[j + 1].key < L.r[j].key){
temp = L.r[j];
L.r[j] = L.r[j + 1];
L.r[j + 1] = temp;
change = true;
}
}
}
python代码实现
'''冒泡排序-BubbleSort'''
def bubble_sort(alist):
for j in range(len(alist)-1,0,-1):
# j表示每次遍历需要比较的次数,是逐渐减小的
for i in range(j):
if alist[i] > alist[i+1]:
alist[i], alist[i+1] = alist[i+1], alist[i]
l = [54, 45, 32, 34, 56, 90]
bubble_sort(l)
print(l)
[32, 34, 45, 54, 56, 90]
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。