【2】对冒泡排序进行改进

【1】中的冒泡排序,我们稍作修改,代码如下:

/*
 * 时间:2014年9月23日 09:54:37
 * By:xxNote
 * Blog:http://www.cnblogs.com/xxNote/articles/3987741.html
 *
 **/
#include <stdio.h>
#define N 10
int arr[N] = {8, 6, 78, 45, 65, 22, 13, 46, 51, 80};
int num;//排序次数
void BubbleSort(void);//从小到大冒泡排序
void Show(void);
int main(void)
{
	printf("排序前数组是:\n");
	Show();
	BubbleSort();

	return 0;
}

void BubbleSort(void)
{
	int i, j, tmp;//i是要排序的趟数,j是每趟要排序的次数
	for (i=0; i<N-1; i++)
	{
		for (j=0; j<N-i-1; j++)
		{
			if (arr[j] > arr[j+1])
			{
				tmp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = tmp;
			}
		}
		printf("第%d趟排序后数组是:\n", num++);
		Show();
	}

	return;
}

void Show(void)
{
	int i;

	for (i=0; i<N; i++)
	{
		printf("%3d", arr[i]);
	}
	printf("\n");

	return;
}

程序的运行结果如下:

 我们看到排序进行0-8共9趟排序,然而在进行了第3趟排序后已经排序完毕,剩下的趟数已经没有必要,因此我们可以设置一个变量flag用来记录本趟有没有进行交换,当本趟比较完的时候发现没有进行交换,那么就说明已经排序完毕直接结束排序即可,代码如下:

/*
 * 时间:2014年9月23日 09:54:37
 * By:xxNote
 * Blog:http://www.cnblogs.com/xxNote/articles/3987741.html
 *
 **/
#include <stdio.h>
#define N 10
int arr[N] = {8, 6, 78, 45, 65, 22, 13, 46, 51, 80};
int num;//排序次数
int flag;//记录本趟排序有没有进行交换,1表示本趟进行过交换
void BubbleSort(void);//从小到大冒泡排序
void Show(void);
int main(void)
{
	printf("排序前数组是:\n");
	Show();
	BubbleSort();

	return 0;
}

void BubbleSort(void)
{
	int i, j, tmp;//i是要排序的趟数,j是每趟要排序的次数
	for (i=0; i<N-1; i++)
	{
		flag = 0;//每趟开始前都清零
		for (j=0; j<N-i-1; j++)
		{
			if (arr[j] > arr[j+1])
			{
				tmp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = tmp;
				flag = 1;//本趟进行过交换
			}
		}
		printf("第%d趟排序后数组是:\n", num++);
		Show();

		//本趟没进行过交换直接退出
		if (flag == 0)
		{
			return;
		}
	}

	return;
}

void Show(void)
{
	int i;

	for (i=0; i<N; i++)
	{
		printf("%3d", arr[i]);
	}
	printf("\n");

	return;
}

运行结果:

可以发现运行的趟数减少了,从而提高了效率。

如果你看完后仍有疑问可以添加我的QQ:1548253108进行详细讨论。

posted @ 2014-09-23 10:19  xxNote  阅读(275)  评论(0编辑  收藏  举报