C语言#冒泡排序

一.基本思路.

1.冒泡排序即是拿第一个数与第二个数作比较,如果第一个数比第二个数大,则两者交换位置(这里我们认为希望得到的是一个升序数列)然后再拿第二个跟第三个数比较,若第二个数大则交换位置,若没有第三个数字大则不交换位置。

2.当一轮比较之后,我们便能得到一个最大的数字,并且它的位置一定是在队列的最后边,这时我们就要注意,下次排序时不再把这个数字加入排序队列当中,能大大提高代码运行效率。

 

下面便是冒泡排序全过程的动态演示图。

 

二.代码实现

#include <stdio.h>
#include <windows.h>
extern int test(int arr[], int sz);//函数声明
int main()
{
	int arr[] = { 2, 5, 6, 4, 8, 9, 28, 16, 12, 18, 15, 17 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
	test(arr,sz);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	system("pause");
	return 0;
}
static void swap(int *xp, int *yp)
{
	int temp = *xp;
	*xp = *yp;
	*yp = temp;
}
int test(int arr[], int sz)
{
	for (int i = 0; i < sz-1; i++)
	{
		for (int j = 0; j < sz - 1 - i; j++){
			if (arr[j]>arr[j + 1]){
				swap(&arr[j], &arr[j + 1]);
			}
		}
	}
}

三.问题发现.

如果数组本就是一个有序的数组,那这样循环就会大大提高了代码的时间复杂度。

 

为解决此问题,那么我们可以定义一个监控的变量,用来监控数组,当进入循环时,一轮循环后,都没有交换任何数值的时候,说明该数列本就是一个有序的数列,我们便不用再执行下去,跳出循环打印结果即可。代码实现如下。

#include <stdio.h>
#include <windows.h>
extern int test(int arr[], int sz);
int main()
{
	int arr[] = { 2, 5, 6, 4, 8, 9, 28, 16, 12, 18, 15, 17 };
	int sz = sizeof(arr) / sizeof(arr[0]);//计算数组的大小
	
	for (int i = 0; i < sz; i++)//循环打印排序前的数组
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
	test(arr,sz);
	for (int i = 0; i < sz; i++)//打印排序后的数组
	{
		printf("%d ", arr[i]);
	}
	system("pause");
	return 0;
}
static void swap(int *xp, int *yp)//利用指针交换两个数的值
{
	int temp = *xp;
	*xp = *yp;
	*yp = temp;
}
int test(int arr[], int sz)
{
	for (int i = 0; i < sz-1; i++)
	{
		int flag = 1;
		for (int j = 0; j < sz - 1 - i; j++){
			if (arr[j]>arr[j + 1]){
				swap(&arr[j], &arr[j + 1]);
				flag = 0;
			}
		}
		if (flag){
			break;
		}
	}
}

 

四.运行结果.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值