码迷,mamicode.com
首页 > 其他好文 > 详细

求数组逆序对

时间:2014-08-04 21:26:48      阅读:262      评论:0      收藏:0      [点我收藏+]

标签: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; }

求数组逆序对,布布扣,bubuko.com

求数组逆序对

标签:io   for   ar   cti   算法   amp   new   c   

原文地址:http://www.cnblogs.com/candycloud/p/3890938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!