数组排序
来源:互联网 发布:矩阵连乘a1 a2 编辑:程序博客网 时间:2024/06/13 13:36
题目描述:
给定一个数组input[],如果数组长度n为奇数,则将数组中最大的元素放到 output[]数组最中间的位置,如果数组长度n为偶数,则将数组中最大的元素放到 output[]数组中间两个位置偏右的那个位置上,然后再按从大到小的顺序,依次在第一个位置的两边,按照一左一右的顺序,依次存放剩下的数。
例如:input[] = {3, 6, 1, 9, 7} output[] = {3, 7, 9, 6, 1}; input[] = {3, 6, 1, 9, 7, 8} output[] = {1, 6, 8, 9, 7, 3}
分析:
首先要先对input数组进行排序,选用快速排序法,因为快速排序法的时间复杂度最优。然后再对排序后的数组按照题目要求进行重排。
代码如下:
#include<stdio.h>#include<stdlib.h>void quick_sort(int *input,int low,int high){ int i=low; int j=high; int p=input[low]; while(i<j) { while(i<j&&input[j]<=p) j--; if(i<j) { input[i]=input[j]; i++; } while(i<j&&input[i]>p) i++; if(i<j) { input[j]=input[i]; j--; } } input[i]=p; if(low<i-1) quick_sort(input,low,i-1); if(j+1<high) quick_sort(input,j+1,high);}void resort(int *input,int *output,int n){ int k=n/2; output[k]=input[0]; int l=k-1,r=k+1; if(n&1==1) { for(int i=1;i<n;i=i+2) { output[l--]=input[i]; output[r++]=input[i+1]; } } else { for(int i=1;i<n-1;i=i+2) { output[l--]=input[i]; output[r++]=input[i+1]; } output[l]=input[n-1]; }}int main(){ int input[]={3,6,1,9,7,8,4,5,2,0}; int output[100]; int n=sizeof(input)/sizeof(int); quick_sort(input,0,n-1); for(int i=0;i<n;i++) printf("%d ",input[i]); printf("\n"); resort(input,output,n); for(int i=0;i<n;i++) printf("%d ",output[i]);}
0 0
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- 数组排序
- Python class
- Android 自定义Dialog类,并在Activity中实现按钮监听事件
- 过滤关联表属性
- 关于九宫格的适配布局
- Linux下Graphite的安装及部署
- 数组排序
- 序列化
- Python 实现进程锁
- Hibernate 缓存机制
- 同行代码审查之我见
- informatica 数据库驱动程序事件,加载库[pmora8.dll]时出错。
- Regular Expression Matching
- PHP中的排序函数sort、asort、rsort、krsort、ksort区别分析
- Windows Codepage: 936 (Simplified Chinese GBK)