求數組逆序對

來源:互聯網
上載者:User

標籤:io   for   ar   cti   演算法   amp   new   c   


思路:類似歸併排序演算法,在合并已經有序的相鄰子數組的時候,計算前面數組相對於後面數組的逆序對數,整個遞迴過程可以算出所有逆序對
#include <stdio.h>void merge(int A[], int front, int middle, int end, int &count){ if (front >= end) return; int i = front; int j = middle + 1; int k = 0; int *p = new int[end - front + 1]; while (i <= middle && j <= end) { if (A[i] < A[j]) { p[k++] = A[i++]; } else { count += middle - i + 1; p[k++] = A[j++]; } } if (j <= end) while (j <= end) { p[k++] = A[j++]; count += middle - i + 1; } if (i <= middle) while (i <= middle) p[k++] = A[i++]; printf("front:%d end:%d :", front, end); for (int i = 0; i < k; ++i) { printf("%d ", p[i]); A[front + i] = p[i]; } printf("\n"); delete [] p;}void merge_sort(int A[], int front, int end, int &count){ if (front >= end) return; int middle = (front + end) / 2; merge_sort(A, front, middle, count); merge_sort(A, middle + 1, end, count); merge(A, front, middle, end, count);}int main(){ int count = 0; int rand[] = {3,1,5,23,2,32,56,76,65,34,2,2,333,1,0}; merge_sort(rand, 0, 4, count); for (int i = 0; i < 5; ++i) { printf("%d ", rand[i]); } printf("\n"); printf("%d\n", count); return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.