Huawei trial-difference sorting, Huawei difference sorting
Sorts the integer array by the difference value from the specified integer and returns the result in ascending order of the difference value.
Implementation Method:
Public staticint [] calcTimes (int [] num, int value );
[Input] num: an integer array;
Integer specified by value
[Return] returns an integer array in ascending order, sorted by the difference between each integer and the specified integer.
[Note] You only need to complete the function algorithm, and there is no IO input or output in the middle.
Example
Input: num = {1, 2, 4, 5, 10, 17,18, 19} value = 5
Return Value: {5, 4, 3, 2, 17,18, 19}
#include <iostream>#include<math.h>using namespace std;int len;int compare(const void *p,const void *q){return *(int *)p-*(int *)q;}void calcTimes(int num[],int value){int i,k,b[100],j=0;for(i=0;i<len;i++){b[j++]=abs(num[i]-value);}qsort(b,len,sizeof(int),compare);for(i=0;i<len;i++)for(k=0;k<len;k++)if(abs(num[k]-value)==b[i]){printf("%d ",num[k]);break;}printf("\n");}int main(){int n,m,i=0,a[100];scanf("%d",&n);while(getchar()!='\n'){a[i++]=n;scanf("%d",&n);}a[i++]=n;len = i;scanf("%d",&m);calcTimes(a,m);return 0;}
Test results may be incomplete. Check for missing information: