Fork me on GitHub

改进版的冒泡排序(双向冒泡算法)

下面是两种一般冒泡算法和双向冒泡算法的对比:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

//一般的冒泡排序
void bubbleSort(int a[], int n)
{
	int i, j, k;
	int temp;

    for (i = 0; i < n; i++){    //最多做n-1趟排序
        for(j = 0 ;j < n - i - 1; j++){   
            if(a[j] > a[j + 1]){    //把大的值交换到后面
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }            
        printf("第%d次排序结果:", i + 1);
        for(k = 0; k < n; k++){
            printf("%d\t", a[k]);
        }
        //printf("\n");
    }
    printf("最终排序结果: ");
    for(k = 0; k < n; k++){
        printf("%d\t", a[k]);
	}
}

//改进版的冒泡排序(双向冒泡)
void bidBubbleSort(int a[], int n)
{
	int left, right, t, l, r, j, i = 0;

	left =0;
	right = n -1;

	//双向冒泡算法,极大的减少了循环排序的次数
	while(left < right)
	{
		//必须要给l和r赋值,否则若数组一开始就有序,则right=r中的r未赋值,即报错
		l = left + 1;
		r = right -1; 

		//第一次循环将最大的值放到末尾
		for(j = left; j < right; j++)
		{
			if(a[j] > a[j + 1])
			{
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t;
				r = j;
			}
		}
		right = r;

		//第二次循环将最小的值放到了开头
		for(j = right; j > left; j--)
		{
			if(a[j] < a[j - 1])
			{
				t = a[j];
				a[j] = a[j - 1];
				a[j - 1] = t;
				l = j;
			}
		}
		left = l;

		printf("第%d次排序结果:", i + 1);
		i++;
        for(j = 0; j < n; j++){
            printf("%d\t", a[j]);
        }
	}
	 printf("最终排序结果: ");
    for(j = 0; j < n; j++){
        printf("%d\t", a[j]);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int score1[] = {98, 69, 75, 47, 89, 90, 100, 70};
	bubbleSort(score1, 8);
	printf("\n");
	int score2[] = {98, 69, 75, 47, 89, 90, 100, 70};
	bidBubbleSort(score2, 8);

	system("pause");
	return 0;
}

 下面是运行效果:

可见,双向冒泡排序能大大减少排序的次数,值得借鉴!!!

 

 

posted @ 2013-03-16 22:08  Alexia(minmin)  阅读(12421)  评论(4编辑  收藏  举报
无觅关联推荐,快速提升流量