一些排序演算法程式

來源:互聯網
上載者:User

#include<iostream><br />using namespace std;<br />#define n 5 //代排序的個數<br />typedef int AnyType;//資料類型<br />struct RecType<br />{<br />int key;<br />AnyType other;//記錄其他資料域<br />};<br />RecType R[n+1];//R[0]用作監視哨<br />void CreateRecType(RecType R[])<br />{<br />cout<<"最多輸入"<<n<<"個數"<<endl;<br />cout<<"請輸入索引值與對應資料"<<endl;<br />int key,other,i=1;<br />while(i<n+1)<br />{<br />cin>>key>>other;<br />R[i].key=key;<br />R[i].other=other;<br />i++;<br />}<br />cout<<"輸入成功!!"<<endl;<br />}<br />void showData(RecType R[])<br />{<br />for(int i=1;i<n+1;i++)<br />{<br />cout<<R[i].key<<" "<<R[i].other<<endl;<br />}<br />}<br />//1.冒泡排序<br />void MaopaoSort(RecType R[],int num)<br />{<br />int i=num,lastExchange;<br />RecType temp;<br />while(i>1)<br />{<br />lastExchange=1;<br />for(int j=0;j<i;j++)<br />{<br />if(R[j].key>R[j+1].key)<br />{<br />temp=R[j];<br />R[j]=R[j+1];<br />R[j+1]=temp;<br />lastExchange=j;<br />}<br />}<br />i=lastExchange;<br />}<br />}</p><p>//2. 快速排序<br />//a.分塊<br />int Partition(RecType R[],int low,int high)<br />{<br />R[0]=R[low];<br />int pivotkey=R[low].key;<br />while(low<high)<br />{<br />while(low<high && R[high].key>=pivotkey)<br />high--;<br />R[low]=R[high];<br />while(low<high && R[low].key<=pivotkey)<br />low++;<br />R[high]=R[low];<br />}<br />R[low]=R[0];<br />return low;<br />}<br />//b.Qsort<br />void QSort(RecType R[],int low,int high)<br />{<br />if(low<high-1)<br />{<br />int location=Partition(R,low,high);<br />QSort(R,low,location-1);<br />QSort(R,location+1,high);<br />}<br />}<br />void QuickSort(RecType R[] ,int num)<br />{<br />QSort(R,1,num);<br />}</p><p>//3.直接選擇排序<br />void SelectSort(RecType R[],int num)<br />{<br />RecType temp;<br />for(int i=1;i<num;i++)<br />{<br />int k=i;<br />for(int j=i+1;j<=num;j++)<br />{<br />if(R[j].key<R[k].key)<br />k=j;<br />if(i!=k)<br />{<br />temp=R[i];<br />R[i]=R[k];<br />R[k]=temp;<br />}<br />}<br />}<br />}</p><p>//4.直接插入排序<br />void InsertSort(RecType R[] ,int num)<br />{<br />for(int i=2;i<=num;i++)//假定第一個記錄有序<br />{<br />R[0]=R[i];<br />int j=i-1;<br />while(R[0].key<R[j].key)<br />{<br />R[j+1]=R[j];<br />j--;<br />}<br />R[j+1]=R[0];<br />}<br />}</p><p>int main()<br />{<br />CreateRecType(R);<br />showData(R);<br />InsertSort(R,n);<br />cout<<"排序後的結果:"<<endl;<br />showData(R);<br />return 0;<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.