! 代码省略了main函数和头文件
C语言: 在main函数中调用 minMoves2( ) 函数
//排序函数
void sortNums( int *nums, int numsSize){
int tmp = 0;
for (int i=0; i<numsSize-1; i++){
int *p = nums;
for(int j=i; j<numsSize-1; j++){
if(*p > *(p+1)){
tmp = *p;
*p = *(p+1);
*(p+1) = tmp;
}
*(p++);
}
}
}
//找中位数函数
void getCenterNum( int *nums, int numsSize, int *centerNum){
int *p = nums;
if( numsSize % 2 == 0){
for(int i=0; i<numsSize/2; i++){
*centerNum = *(p+1);
*(centerNum+1) = *(p);
*(p++);
}
}
else{
for(int i=0; i<numsSize/2+1; i++){
*centerNum = *p;
*(p++);
}
printf("*centerNum = %d\n*(centerNum+1) = %d\n%d\n", *centerNum, *(centerNum+1),*p);
}
}
//计算结果
int getResult(int *nums,int number, int numsSize){
int result = 0;
int *p = nums;
for(int i=0; i<numsSize; i++){
if (*p > number){
result += *p - number;
}
else{
result += number - *p;
}
*(p++);
}
return result;
}
int minMoves2(int* nums, int numsSize) {
//1:数组排序
sortNums( nums, numsSize);
//2:找到中位数
int centerNum[2]= {-1, -1};
//将中位数赋值给数组
getCenterNum(nums, numsSize, centerNum);
//如果数组内不是一个正整数,则有两个中值
if (*(centerNum + 1) != -1){
//中间两个数哪个数和数组所有元素的差小
int result_left = getResult(nums,*centerNum,numsSize);
int result_right = getResult(nums, *(centerNum+1), numsSize);
return result_left > result_right ? result_right : result_left ;
}
else{
//如果中位数数组里只有一个整数,直接计算nums数组每个数和中位数的差
return getResult(nums, *centerNum, numsSize);
}
return 0;
}