/* 普通冒泡排序 */
void BubbleSort(int *arr,int n){
int temp;
for(int i = 0;i!=n-1;i++){
for(int j = 0;j!=n-i;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
/* 改进版的冒泡排序 */
void BubbleSort_advance(int *arr,int n){
int position,bound,temp;
position = n-1;
while(position){
bound = position;
position = 0;
for(int j = 0;j!=bound;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
position = j;
}
}
for(int i = 0;i!=n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
}
改进版冒泡算法:
设置一个标志位,标志每趟排序过程中,比较到的最后一个位置,并在每次循环开头将其设置为0,当一次排序中没有交换时,标志位为0,停止循环。通过这种方法,以减少循环次数,提高算法性能。
Ps: ① 在循环中,注意循环终止的条件,尤其是数组边界,一定要确定好再动手。