思路:类似归并排序算法,在合并已经有序的相邻子数组的时候,计算前面数组相对于后面数组的逆序对数,整个递归过程可以算出所有逆序对#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; }
时间: 2024-10-11 17:44:46