1、冒泡排序是非常容易理解和实现,,以从小到大排序举例:
设数组长度为N。
1.比较相邻的前后二个数据,如果前面数据大于后面的数据,就将二个数据交换。
2.这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第N-1个位置。
3.N=N-1,如果N不为0就重复前面二步,否则排序完成。
//冒泡排序
void Swap(int& a, int& b){
int temp = a;
a = b;
b = temp;
}
void BubbleSort1(int a[], int n){
for (int i = 0; i < n; i++){
for (int j = 1; j < n - i; j++){
if (a[j] < a[j-1]){
Swap(a[j], a[j - 1]);
}
}
}
}
2、冒泡排序改进算法1:
每趟排序中进行正向和反向两遍冒泡的方法一次可以得到两个最终值(最大者和最小者) , 从而使排序趟数几乎减少了一半。
//冒泡排序改进算法1
void Swap(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
void BubbleSort2(int A[], int n){
int low = 0;
int high = n - 1;
int i=0;
while (low<high){
for (i = low; i<high; i++){
if (A[i]>A[i + 1]){
Swap(A[i], A[i + 1]);
}
}
high--;
for (i = high; i>low; i--){
if (A[i] < A[i - 1]){
Swap(A[i], A[i - 1]);
}
}
low++;
}
}
3、冒泡排序改进算法2:
设置一标志性变量pos,用于记录每趟排序中最后一次进行交换的位置。由于pos位置之后的记录均已交换到位,故在进行下一趟排序时只要扫描到pos位置即可。
//冒泡排序改进算法2
void BubbleSort3(int A[],int n){
int high=n-1;
int pos=0;
while(high>0){
for(int i=0;i<high;i++){
if(A[i]>A[i+1]){
Swap(A[i],A[i+1]);
pos=i;
}
}
high=pos;
}
}