歸並排序求逆序對
阿新 • • 發佈:2019-02-26
bsp mergesort n) while ges ret turn print style
#include<stdio.h> void Merge(int ,int ,int ); void mergeSort(int ,int ); int ch[20000],temp[20000]; int count = 0; void mergeSort(int lo,int hi) { if(lo < hi) { int mid =( lo + hi ) / 2; mergeSort(lo,mid); mergeSort(mid + 1,hi); Merge(lo,mid,hi); } }void Merge(int lo,int mid,int hi) { int i = lo; int j = mid + 1; int x = lo; while(i <= mid&&j <= hi) { if ( ch[i] > ch[j]) { count+= mid - i + 1; temp[x++] = ch[j++]; } else { temp[x++] = ch[i++]; } } while(i <= mid) temp[x++] = ch[i++]; while(j <= hi) temp[x++] = ch[j++]; for(int k = lo; k <= hi ; k++) ch[k] = temp[k]; } int main() { int N; scanf("%d",&N); for(int i=0; i < N; i++) { scanf("%d",&ch[i]); } mergeSort(0,N-1); printf("%d\n",count); return 0; }
歸並排序求逆序對