C++歸併演算法執行個體_C 語言

來源:互聯網
上載者:User

本文執行個體講述了C++歸併演算法。分享給大家供大家參考。具體如下:

/*  歸併演算法:把兩個或兩個以上的線性表合并在一起,形成一個新的線性表 函數模版的基本使用 程式意圖:將兩個相同類型的線性表元素排好序,然後將他們組合成一個排好的線性表 */#include <iostream>using namespace std;const int n = 5; //5個元素 //輸出資料元素template <class T1>void OutPut(T1 out[(2*n)]){   for (int i=0; i<(2*n); i++)  {   cout<<out[i]<<" ";  }  cout<<endl;} //輸入資料元素 template <class T2>void InPut(T2 in[n]){  cout<<"請輸入5個資料元素:";  for (int i=0; i<n; i++)  {   cin>>in[i];  cout<<" ";   }  cout<<endl;}//模版函數 輸入線性表元素並將其排序template <class T3> void MySort(T3 a[2*n]){  int temp; //交換資料臨時變數   //冒泡錨序   for (int i=0; i<2*n-1; i++)  {   for (int j=0; j<2*n-1-i; j++)   {    if (a[j]>a[j+1])     {    temp = a[j];    a[j] = a[j+1];    a[j+1] = temp;     }   }  }}//模版函數 歸併 template <class T> void MergeList(T La[n], T Lb[n], T Lc[(2*n)]) {  int i = 0; //作為La的下標   int j = 0; //Lb下標  int k = 0; //Lc下標   //將La Lb組合成在一起   while (i<n && j<n)  {   if (La[i] < Lb[j])   {    Lc[k] = La[i];    k++;    Lc[k] = Lb[j];   }   else   {    if (La[i] == Lb[j])    {     Lc[k] = La[i];     k++;     Lc[k] = Lb[j];    }    else    {     Lc[k] = Lb[j];     k++;     Lc[k] = La[i];    }   }   //各下標往下移動    i++;   j++;   k++;  }   //如果La中的資料沒有取完,及La比Lb長,則將La剩下的元素插入Lc中 這裡是進行擴充   while (i<=n)  {   Lc[k++] = La[i++];  }   //如果Lb中的資料沒有取完,及Lb比La長,則將Lb剩下的元素插入Lc中  while (j<=n)  {    Lc[k++] = Lb[j++];  }   //對組合好的元素進行排序   MySort(Lc); }int main(){ int a1[n],a2[n], a[(2*n)]; double b1[n], b2[n],b[(2*n)]; char m1[n], m2[n], m[(2*n)]; //輸入資料 歸併輸出  /*InPut(a1); InPut(a2);  MergeList(a1,a2,a); OutPut(a); */ InPut(m1); InPut(m2);  MergeList(m1,m2,m); OutPut(m);  system("pause"); return 0;} 

希望本文所述對大家的C++程式設計有所協助。

聯繫我們

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