2012届华为校园招聘上机考试题目第2题——排序问题
给定一个数组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}
#include <stdio.h>
#include <conio.h>//getch()函数所需头文件
#include <stdlib.h>//随机函数所需头文件
#include <time.h>//time()函数所需头文件
int start(void)
{
puts("笔试题第二题");
puts("按任意键开始,按Esc键结束:");
if ( '\x1b' == getch() ) //"\x1b"代表的是Esc键
{
exit(1);
}
}
//初始化Input数组
int *initArray( int *input, int Length )
{
int i;
input = (int *)calloc( Length, sizeof(int) );
srand(time(NULL));
puts("原数组:");
for ( i=0; i < Length; i++ )
{
input[i] = rand()%100;
printf("%d ", input[i] );
}
puts("");
return input;
}
//进行排序,并按题目要求输出到output数组
int *sort( int *input, int *output, int Length )
{
int i,j,k;
int temp;
int middle = Length / 2;
for ( i=0; i < Length; i++)
{
for ( j=i; j < Length; j++)
{
if ( input[i] < input[j] )
{
temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
}
//实现题目要求
j = middle - 1;
k = middle + 1;
output[middle] = input[0];
printf("按降序排列:\n");
for ( i=0; i < Length; i++)
{
printf("%d ", input[i]);
}
puts("");
for ( i=1; i < Length; i++)
{
if ( j >= 0 )
{
output[j--] = input[i];
}
i++;
if ( k < Length )
{
output[k++] = input[i];
}
}
return output;
}
int main()
{
int i;
int *Input = NULL;
int *Output = NULL;
int Length;
while ( 1 )
{
system("cls");
start();
puts("请初始化数组的大小");
scanf("%d", &Length );
fflush(stdin);
Input = initArray( Input , Length);
Output = (int *)calloc( Length, sizeof(int) );
Output = sort( Input, Output, Length );
puts("按题目要求排列:");
for ( i=0; i < Length; i++)
{
printf("%d ", Output[i] );
}
puts("");
free( Input );
free( Output );
system("pause");
}
return 1;
}
测试截图: