Problem:
Existing integer array int input[]={...};
If the number of array elements is odd, the middle one is the largest, the first on the left is the second, the right one again ... After this sort, the leftmost second small, the rightmost smallest
If the number of array elements is even, then the right side of the middle two is the largest, the left first second, the right the first again ... After this sort, the rightmost second small, leftmost smallest
Example:
Odd number of such as: input[]={3,4,8,1,9};
After sorting: input[]={3,8,9,4,1};
An even number of such as: input[]={3,4,8,1,9,6};
After sorting: input[]={1,4,8,9,6,3};
Ideas:
Write a formula, index=x (n); with n from 0->n, the X (n) from the middle position, left 1-> right 1 ... So until the end:
X (n) =imiddle+ ( -1) INDEXINDEX/2;
That is, the first number is imiddle+ (+1) *0
The second number is imiddle+ (-1) *1/2 (after rounding is iMiddle-1)
The third number is imiddle+ (+1) *2/2 (i.e. imiddle+1)
Then sort them with a sort algorithm.
1#include <iostream>2#include <math.h>3 using namespacestd;4 5InlineintIcalcindex (intIinmiddle,intiinserial)6 {7 returnIinmiddle+pow (-1, iinserial) *iinserial/2;8 }9 Ten intMain () One { A intInput[] = {1,2,3,4,5}; - intIcountofinput =sizeof(input)/sizeof(int); - intImiddle = icountofinput/2; the inttemp =0; - intIindexsmall =0; - intIindexbig =0; - + for(intI=0; i<icountofinput; i++) - { + for(intj=0; j<icountofinput-i; J + +) A { atIindexsmall =Icalcindex (imiddle,j); -Iindexbig = Icalcindex (imiddle,j+1); - - if(input[iindexsmall]<Input[iindexbig]) - { - /*temp = Input[iindexsmall]; in Input[iindexsmall] = Input[iindexbig]; - Input[iindexbig] = temp;*/ toinput[iindexsmall]=input[iindexsmall]^Input[iindexbig]; +Input[iindexbig] = input[iindexsmall]^Input[iindexbig]; -Input[iindexsmall] = input[iindexsmall]^Input[iindexbig]; the } * } $ }Panax Notoginseng - for(intI=0; i<icountofinput; i++) thecout<<Input[i]; +cout<<Endl; A the return 0; +}
Operation Result:
24531
Expected (if the input is changed to 123456, the result is 135642)
C + + algorithm sort descending order from center to left