数组排序
问题描述
给定一个长度为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");
}