冒泡排序

冒泡排序基本格式

 1 //c
 2 typedef int elemtype;
 3 void BubbleSort(elemtype *a,int n){
 4     for(int i=0;i<n-1;i++){
 5         for(int j=0;j<n-i-1;j++){
 6             if(a[j]>a[j+1]){
 7                 elemtype tmp=a[j];
 8                 a[j]=a[j+1];
 9                 a[j+1]=tmp;
10             }
11         }
12     }
13 }
 1 # python
 2 def BubbleSort(lst,n):
 3   for i in range(n-1):
 4     for j in range(n-i-1):
 5       if lst[j]>lst[j+1]:
 6         lst[j],lst[j+1]=lst[j+1],lst[j]
 7 
 8 
 9 lst=[4,3,2,6,7,8,4,3,-4,0]
10 BubbleSort(lst,len(lst))
11 print(lst)

由于存在某趟交换后整个序列已经有序

因此加入哨兵,检测这一情况,减少多余操作

 1 //c
 2 typedef int elemtype;
 3 void BubbleSort(elemtype *a,int n){
 4     int f;
 5     for(int i=0;i<n-1;i++){
 6         f=1;
 7         for(int j=0;j<n-i-1;j++){
 8             if(a[j]>a[j+1]){
 9                 elemtype tmp=a[j];
10                 a[j]=a[j+1];
11                 a[j+1]=tmp;
12                 f=0;
13             }
14         }
15         if(f)
16             break;
17     }
18 }
 1 # python
 2 def BubbleSort(lst,n):
 3   for i in range(n-1):
 4     f=True
 5     for j in range(n-i-1):
 6       if lst[j]>lst[j+1]:
 7         lst[j],lst[j+1]=lst[j+1],lst[j]
 8         f=False
 9     if f:
10       break
11 
12 
13 lst=[4,3,2,6,7,8,4,3,-4,0]
14 BubbleSort(lst,len(lst))
15 print(lst)

到这儿就结束了

原文地址:https://www.cnblogs.com/tenjl-exv/p/9973484.html