zoukankan      html  css  js  c++  java
  • 求数组逆序对


    思路:类似归并排序算法,在合并已经有序的相邻子数组的时候,计算前面数组相对于后面数组的逆序对数,整个递归过程可以算出所有逆序对
    #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(" "); 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(" "); printf("%d ", count); return 0; }
  • 相关阅读:
    【POJ
    【OpenJ_Bailian
    【Aizu
    【OpenJ_Bailian
    leetcode-746-Min Cost Climbing Stairs(动态规划)
    leetcode-744-Find Smallest Letter Greater Than Target(改进的二分查找)
    leetcode-728-Self Dividing Numbers
    leetcode-717-1-bit and 2-bit Characters
    leetcode-697-Degree of an Array
    leetcode-682-Baseball Game
  • 原文地址:https://www.cnblogs.com/candycloud/p/3890938.html
Copyright © 2011-2022 走看看