快速排序,堆排序,希爾排序,插入排序

來源:互聯網
上載者:User

1.快速排序

#include <iostream><br />using namespace std;</p><p>void qsort(int a[],int i,int j);<br />//快速排序<br />void main()<br />{<br />int a[]={49,38,65,97,76,13,27};<br />qsort(a,0,6);<br />for (int i=0;i<=6;i++)<br />{<br />cout<<a[i]<<" ";<br />}<br />cout<<endl;<br />}<br />int part(int a[],int i,int j)<br />{</p><p>int key=a[i];<br />while(i<j)<br />{<br />while(i<j&&a[j]>=key)<br />j--;<br />a[i]=a[j];<br />while (i<j&&a[i]<key)<br />i++;<br />a[j]=a[i];<br />}<br />a[i]=key;<br />return i;<br />}<br />void qsort(int a[],int i,int j)<br />{<br />int loc = part(a,i,j);<br />if (loc==i||loc==j)<br />{<br />return;<br />}<br />qsort(a,0,loc-1);<br />qsort(a,loc+1,j);<br />}<br />

 

2.堆排序

堆排序的思想,利用完全二叉樹的形式,孩子結點比父結點大,從n/2~0篩選一次。

 #include <iostream><br />using namespace std;<br />void heapsort(int a[],int n);<br />void main()<br />{<br />int a[]={49,38,65,97,76,13,27};<br />//堆排序<br />heapsort(a,6);<br />for (int i=0;i<=6;i++)<br />{<br />cout<<a[i]<<" ";<br />}<br />cout<<endl;<br />}</p><p>void sift(int a[],int i,int n)<br />{<br />int child,temp;<br />for (temp=a[i];2*i<n;i=child)<br />{<br />child = 2*i;<br />if ((child!=n) && (a[child]<a[child+1]))<br />{<br />child++;//取子節點較大的<br />}<br />if (temp<a[child])<br />{<br />a[i]=a[child];//交換<br />}<br />else<br />break;<br />}<br />a[i]=temp;<br />}</p><p>void heapsort(int a[],int n)<br />{<br />int temp;<br />//1.建堆<br />for (int i=n/2;i>=1;i--)<br />{<br />sift(a,i,n);<br />}<br />//2.調整堆<br />for (i=n;i>=2;i--)<br />{<br />//交換堆頂和第一個<br />temp=a[1];<br />a[1]=a[i];<br />a[i]=temp;<br />sift(a,1,i-1);<br />}<br />}

 

3.shell排序

遞迴增量排序,實際上是插入排序的修改,將插入排序的遞增變數1修改為d即可。

void shellsort(int a[],int n)<br />{<br />int i,j,d;<br />d= n / 2;<br />while (d > 0)<br /> {<br />//以d為間隔的插入排序<br /> for ( i = d; i < n; i++ )<br /> {<br /> int temp = a[i];<br /> for (j=i-d;j>=0&&a[j]>temp;j-=d)<br />a[j + d] = a[j];<br /> a[j + d] = temp;<br /> }<br /> d = d/2;<br /> }<br />}

 

4.插入排序

void insertsort(int a[],int n)<br />{ </p><p>for (int i=0;i<n;i++)<br />{<br />int temp = a[i];<br />for (int j=i-1;j>=0 && a[j]>temp;j--)<br />{<br />a[j+1]=a[j];<br />}<br />a[j+1]=temp;//因為j最後減1,所以為a[j+1]<br />}<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.