java實現快速排序演算法

來源:互聯網
上載者:User
void paixu(int a[],int low,int high;)//用快速排序法
...{
  // low, high表示掃描的範圍

  int pivot;//存放中心索引及其值的局部變數
  int scanup,scandown,mid;//用於掃描的索引
  if (high-low<=0) //如果數組中的元素少於兩個,則返回
   return;
  else 
   if(high-low==1) //如果有兩個元素,對其進行比較
   ...{
    if(apai[high]<apai[low]) //如果後一個比前一個小,
     Swap(apai[low],apai[high]);//那麼交換位置
     return;
   }//end if
  mid=(low+high)/2;//取得中心索引
  pivot=apai[mid];//將中間索引的值,賦給pivot
  Swap(apai[mid],apai[low]);//交換pivot及低端元素的值
  Scanup=low+1;
  Scandown=high;//初始化掃描索引scanup和scandown
  do...{
   //從低端子表向上掃描,當scanup進入高端子表或遇到大於pivot的元素時結束.
   while(scanup<=scandown && apai[scanup]<=pivot)
    scanup++;
    //從高端子表向下掃描,當scandown遇到小於或等於pivot的元素時結束
   while(piovt<apai[scandown])
    scandown--;
    //如果兩個索引還在各自的子表中,則表示兩個元素錯位,將兩個元素換位
    if(scanup<scandown)
     Swap(apai[scanup],apai[scandown]);
  }while(scanup<scandown);
  //將pivot拷貝到scandown位置,分開兩個子表
  apai[low]=apai[scandown];
   apai[scandown]=pivot;
  //如果低端子表(low至scandown-1)有2個或更多個元素,則進行遞迴調用
  if(low<scandown-1)
   paixu(apai,low,scandown-1);
   //如果高端子表(scandown+1至high) 有2個或更多個元素,則進行遞迴調用
  if(scandown+1<high)
   paixu(apai, scandown+1, high);
}
 

聯繫我們

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