例题1-5 三整数排序

输入3个整数,从小到大排序后输出

样例输入:

20 7 33

样例输出:

7 20 33

#include <stdio.h>
int main()
{
	int a,b,c,t;
	scanf("%d%d%d",&a,&b,&c);
	if(a>b)
	{
	  t=a;
	  a=b;
	  b=t;	
	}
	if(a>c)
	{
	  t=a;
	  a=c;
	  c=t;	
	}
	if(b>c)
	{
	  t=b;
	  b=c;
	  c=t;	
	}
	printf("%d %d %d",a,b,c);
	return 0;
}
思路:冒泡排序原型
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,折半排序也叫做二分查找排序,是一种基于比较的排序算法。其基本思想是:将一个序列分成两个子序列,然后对每个子序列再进行折半排序,最终将两个有序的子序列合并成一个有序的序列。 下面以一个例题来说明折半排序的实现过程。 问:给定一个长度为n的整数序列,将其按升序排列。 解思路: 1. 将序列分成两个子序列,分别进行折半排序。 2. 将两个有序的子序列合并成一个有序的序列。 代码实现: ``` void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } ``` 该代码实现了折半排序的基本思路,先将序列分成两个子序列,然后递归地对每个子序列进行折半排序,最后合并两个有序的子序列成一个有序的序列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值