O(nlogn)实现逆序数求值

来源:互联网 发布:ipv6网络电视直播 编辑:程序博客网 时间:2024/06/10 12:41
const int LENGTH=100;int temp[LENGTH];  //额外的辅助数组int count=0;void Merge(int * array,int first,int med,int last){int i=first,j=med+1;int cur=0;while (i<=med&&j<=last){if (array[i]<array[j]){temp[cur++]=array[i++];}else{temp[cur++]=array[j++];<span style="color:#ff0000;">count+=med-i+1</span>;  //核心代码,逆序数增加}}while (i<=med){temp[cur++]=array[i++];}while (j<=last){temp[cur++]=array[j++];}for (int m=0;m<cur;m++){array[first++]=temp[m++];}}void MergeSort(int *array,int first,int last){if (first==last){return ;}int med=first+(last-first)/2;MergeSort(array,first,med);MergeSort(array,med+1,last);Merge(array,first,med,last);}

0 0