将排序数组按绝对值大小排序 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
排序的数组有可能包含正负, 可以使用折半查找确定中值位置, 然后再使用两个指针, 顺次排序两端.
解决思路是:
1.数组中的元素全为正,返回;
2.数组中的元素全为负,返回;
3.数组中有正数有负数,就用二分法查找,判断中间元素的符号
a)中间元素为正,继续判断中间元素前面一个元素的符号;
b)中间元素为负,判断中间元素后一个元素的符号;
c)中间元素为零,令其等于结果值返回;
时间复杂度O(nlogn)
代码:
/*
* main.cpp
*
* Created on: 2014.9.12
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void Reverse(int* begin, int* end) {
while (begin < end) {
int tmp = *begin;
*begin++ = *end;
*end-- = tmp;
}
}
void AbsoluteSort(int res[], int data[], const int length) {
if (data == NULL || length <= 0) {
res = data;
return;
}
if ((data[0]<0 && data[length-1]<0) || (data[0]>0 && data[length-1]>0)) {
res = data;
return;
}
int left = 0;
int right = length-1;
int mid;
while (left < right) {
mid = left + ((right-left)>>1);
if (data[mid]>0 && data[mid-1]<=0) {
right = mid; left = mid-1;
break;
} else if (data[mid]>0) {
right = mid;
} else if (data[mid]<0 && data[mid+1]>=0) {
left = mid; right = mid+1;
break;
} else if (data[mid]<0) {
left = mid;
} else {
break;
}
}
int num=0;
while (right < length && left >=0) {
if (abs(data[right]) <= abs(data[left])) {
res[num++] = data[right++];
} else {
res[num++] = data[left--];
}
}
while (right < length)
res[num++] = data[right++];
while (left >=0 ) {
res[num++] = data[left--];
}
}
int main (void) {
int data[] = {-5, -4, -2, -1, 0, 1, 2, 6};
const int length = sizeof(data)/sizeof(data[0]);
int res[length];
AbsoluteSort(res, data, length);
for (int i=0; i<length; ++i) {
printf("%d ", res[i]);
}
printf("\n");
}
输出:
0 1 -1 2 -2 -4 -5 6