蓝桥杯试题集基础练习之数组排序

数组排序

问题描述

给定一个长度为n的数列,将这个数列按从小到大的顺序排列。1<=n<=200
输入格式
  第一行为一个整数n。
  第二行包含n个整数,为待排序的数,每个整数的绝对值小于10000。
输出格式
  输出一行,按从小到大的顺序输出排序后的数列。
样例输入
5
8 3 6 4 9
样例输出
3 4 6 8 9

C++源代码

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
	int length;
	scanf("%d",&length);
	int a[length];
	int i=0;
	while(i<length){
		cin>>a[i];//录入数组元素 
		i++;	
	}
	//开始二分排序
	for(i=1;i<length;i++){
		int temp = a[i];//保存当前元素 
		int low = 0;
		int high = i-1;/
		while(low<=high){//在a[low...high]中折半查找有序插入的位置 
			int mid = (low + high)/2;
			if(a[mid]>temp)//如果中间值大于temp,high前移至mid-1位置 
				high = mid-1;
			else//如果中间值小于temp,low值后移至mid+1位置 
				low = mid+1;		
		}
		for(int j=i-1;j>high;j--){//元素后移等待插入 
			a[j+1] = a[j];
		}
		a[high+1] = temp;//当前元素插入 
	}
	for(i=0;i<length;i++){//遍历输出 
		printf("%d ",a[i]);
	}
	printf("\n"); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值