• 数组奇偶数排序


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

    函数接口 void sort(int input[], int n, int output[])

     

     1 #include<stdio.h>
     2 void sort(int input[], int n, int output[])
     3 {
     4     int i,j,k;
     5     for (i=0; i < n-1; i++)
     6         for (j=1; j < n-i; j++)
     7     {
     8         if (input[j-1] < input[j])
     9         {
    10             int t = input[j-1];
    11             input[j-1] = input[j];
    12             input[j] = t;
    13         }
    14     }
    15     for (int i=0; i < n; i++)
    16         printf("%d ",input[i]);
    17     printf("
    ");
    18     if (n % 2 == 1)
    19     {
    20         i = n / 2;
    21         j = n /2 + 1;
    22         k = 0;
    23         output[i--] = input[k++];
    24         for (; k < n; ){
    25             output[i--] = input[k++];
    26             output[j++] = input[k++];
    27         }
    28     }
    29     else
    30     {
    31         j = n / 2;
    32         i = n / 2 - 1;
    33         for (k=0; k < n; ){
    34             output[j++] = input[k++];
    35             output[i--] = input[k++];
    36         }
    37     }
    38 }
    39 int main()
    40 {
    41     int n,input[100],output[100];
    42     scanf("%d",&n);
    43     for (int i=0; i < n; i++)
    44     {
    45         scanf("%d",&input[i]);
    46     }
    47     sort(input,n,output);
    48     for (int i=0; i < n; i++)
    49         printf("%d ",output[i]);
    50     printf("
    ");
    51 }

  • 相关阅读:
    11、sqlite
    10、正则
    9、bs4
    8、异常与import
    7、文件
    6、函数
    4、字典及集合
    3、元组
    1、python基本语法
    shell编程 15 --- shell 脚本调试技巧
  • 原文地址:https://www.cnblogs.com/george-cw/p/3936181.html
Copyright © 2020-2023  润新知