【演算法】C#快速排序類

來源:互聯網
上載者:User

快速排序的基本思想是基於分治策略的。對於輸入的子序列ap..ar,如果規模足夠小則直接進行排序,否則分三步處理:

分解(Divide):將輸入的序列ap..ar劃分成兩個非空子序列ap..aq和aq+1..ar,使ap..aq中任一元素的值不大於aq+1..ar中任一元素的值。 

遞迴求解(Conquer):通過遞迴對p..aq和aq+1..ar進行排序。 

合并(Merge):由於對分解出的兩個子序列的排序是就地進行的,所以在ap..aq和aq+1..ar都排好序後不需要執行任何計算ap..ar就已排好序。 

這個解決流程是符合分治法的基本步驟的。因此,快速排序法是分治法的經典應用執行個體之一。

using System;

namespace VcQuickSort

{

 /// <summary>

 /// ClassQuickSort 快速排序。

 /// </summary>

 public class QuickSort

 {

  public QuickSort()

  {

  }

  private void Swap(ref int i,ref int j)

  //swap two integer

  {

   int t;

   t=i;

   i=j;

   j=t;

  }

  

  public void Sort(int [] list,int low,int high)

  {

   if(high<=low)

   {

    //only one element in array list

    //so it do not need sort

    return;

   }

   else if (high==low+1)

   {

    //means two elements in array list

    //so we just compare them

    if(list[low]>list[high])

    {

     //exchange them

     Swap(ref list[low],ref list[high]);

     return;

    }

   }

   //more than 3 elements in the arrary list

   //begin QuickSort

   myQuickSort(list,low,high);

  }

  public void myQuickSort(int [] list,int low,int high)

  {

   if(low<high)

   {

    int pivot=Partition(list,low,high);

    myQuickSort(list,low,pivot-1);

    myQuickSort(list,pivot+1,high);

   }

  }

  private int Partition(int [] list,int low,int high)

  {

   //get the pivot of the arrary list

   int pivot;

   pivot=list[low];

   while(low<high)

   {

    while(low<high && list[high]>=pivot)

    {

     high--;

    }

    if(low!=high)

    {

     Swap(ref list[low],ref list[high]);

     low++;

    }

    while(low<high && list[low]<=pivot)

    {

     low++;

    }

    if(low!=high)

    {

     Swap(ref list[low],ref list[high]); 

     high--;

    }

   }

   return low;

  }

 }

}

相關文章

聯繫我們

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