标签:style blog class code c tar
设A[1…n]是一个包含n个不同数的数组。如果在i<j的情况下,有A[i]>A[j],则(i,j)就称为A中的一个逆序对(inversion)【《算法导论》2-4】
现给出一个数列,求该数列中的逆序对(逆序对 )
利用归并排序的方法我们给出如下算法:
// // main.cpp // CpushTest // // Created by Ellen on 14-5-11. // Copyright (c) 2014年 andy. All rights reserved. // #include <iostream> using namespace std; static int specialtime=0; void mergeSort(int *A,int left,int mid,int right) { int *L=new int[mid-left+1]; int *R=new int[right-mid+1]; int i,j; for(i=0;i<mid-left+1;i++) { L[i]=A[left+i]; } for (j=0; j<right-mid; j++) { R[j]=A[mid+j+1]; } i=0,j=0; int k=left; while(i<mid-left+1 && j<right-mid) { if(L[i]<=R[j]) { A[k++]=L[i++]; }else { A[k++]=R[j++]; specialtime+=mid-left+1-i; } } while (i<mid-left+1) { //specialtime++; A[k++]=L[i++]; } while (j<right-mid) { A[k++]=R[j++]; } delete []L; delete []R; } void merge(int *A,int left,int right) { if (left<right) { int mid=(right-left)/2+left; merge(A,left,mid); merge(A,mid+1,right); mergeSort(A,left,mid,right); } } int main(int argc, const char * argv[]) { int A[]={100,11,43,65}; //int A[]={56,3,5,68,100,32}; //int A[]={68,100,32}; merge(A,0,sizeof(A)/sizeof(int)-1); for(int i=0;i<sizeof(A)/sizeof(int);i++) { cout<<A[i]<<" "; } cout <<endl; cout<<"逆序对是 "<<specialtime<<endl; return 0; }
标签:style blog class code c tar
原文地址:http://blog.csdn.net/richard_rufeng/article/details/25560655