第二章之“逆序對數目”(思考題2-4)

來源:互聯網
上載者:User

設計用時間複雜度為O(nlgn)的演算法對長度為n的數組中的逆序對計數。

核心思想就是修改合并排序演算法,因為當合并時會比較兩個連續小數組中元素的大小。

#include <stdio.h>#include <string.h>#include <time.h>#define BUFFER_SIZE 10void Merge(int *a,int p,int q,int r,int *cnt){int i=0;int j=0;int k=0;int n1=q-p+1;int n2=r-q;int n=n1+n2;int b[n1+1];int c[n2+1];memset(b,0,sizeof(b));memset(c,0,sizeof(c));b[n1]=BUFFER_SIZE;//哨兵元素,注意別溢出 c[n2]=BUFFER_SIZE;//哨兵元素,注意別溢出for(i=p,j=0;i<=q;i++){b[j]=a[i];j++;}for(i=q+1,k=0;i<=r;i++){c[k]=a[i];k++;}for(i=p,j=0,k=0;i<=r;i++){if(b[j]<=c[k]){a[i]=b[j];j++; }else{a[i]=c[k];k++;(*cnt)++; //出現逆序對,計數}}}void MergeSort(int *a,int p,int r,int *cnt){int q=0;if(p>=r){return;}q=(p+r)/2;MergeSort(a,p,q,cnt);MergeSort(a,q+1,r,cnt);Merge(a,p,q,r,cnt);} void Output(int *a,int len){int i=0;for(i=0;i<len;i++){printf("%d ",a[i]);}printf("\n");}int main(){int i=0;int k=1;int cnt=0;//計算逆序對數目 int a[BUFFER_SIZE];memset(a,0,sizeof(a));srand((unsigned)time(NULL));for(i=0;i<BUFFER_SIZE;i++){a[i]=rand()%BUFFER_SIZE;}printf("隨機產生的數組:"); Output(a,BUFFER_SIZE);printf("冒泡排序後:"); MergeSort(a,0,BUFFER_SIZE-1,&cnt);Output(a,BUFFER_SIZE);printf("逆序對的數目為:%d\n",cnt); system("pause");return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.