編程演算法 - 將排序數組按絕對值大小排序 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   排序數組   絕對值排序   c++   

將排序數組按絕對值大小排序 代碼(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 





編程演算法 - 將排序數組按絕對值大小排序 代碼(C)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.