zoukankan      html  css  js  c++  java
  • 2012届华为上机试题之C语言排序

    给定一个数组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}

    题目考察的是排序+规格化输出:

    容易让人理解的解法,首先进行排序,进而进行排序后的输出:

     1 #include <iostream>
     2 #include <algorithm>
     3 using namespace std;
     4 #define SIGN(x) ((x)>=0)?(1):(-1)
     5 #define N 5
     6 int Input[N]={36197};
     7 int Output[N];
     8 
     9 void formatIO(int* input,int* output,int n)
    10 {
    11     int m=(N>>1);
    12     int slid=-1;
    13     if(N&0x01==0)
    14     {
    15         m+=1;
    16     }
    17     output[m]=Input[N-1];
    18     for(int i=N-2;i>=0;i--)
    19     {
    20         output[m+slid]=input[i];
    21         if(slid>0)slid=-(slid+1);
    22         else slid=-(slid);
    23     }
    24 }
    25 
    26 int main()
    27 {
    28     sort(Input,Input+N);//从小到大排序
    29     formatIO(Input,Output,N);
    30     for(int i=0;i<N;i++)
    31     {
    32         cout<<Output[i]<<",";
    33     }
    34     cout<<endl;
    35     return 1;

    36 } 

  • 相关阅读:
    215. Kth Largest Element in an Array
    214. Shortest Palindrome
    213. House Robber II
    212. Word Search II
    210 Course ScheduleII
    209. Minimum Size Subarray Sum
    208. Implement Trie (Prefix Tree)
    207. Course Schedule
    206. Reverse Linked List
    sql 开发经验
  • 原文地址:https://www.cnblogs.com/weisteve/p/2179829.html
Copyright © 2011-2022 走看看