面試常考各類排序演算法總結.(c#)

來源:互聯網
上載者:User

標籤:開始   color   public   ble   bsp   遍曆   大於   demo   ons   

一. 面試以及考試過程中必會出現一道排序演算法面試題,為了加深對排序演算法的理解,在此我對各種排序演算法做個總結歸納。

1.冒泡排序演算法(BubbleSort)

 1 public Class SortDemo 2 { 3      public void BubbleSort(int arr) 4      { 5             int temp=0; 6           //需要走arr.Length-1 趟 7            for(int i=0;i<arr.Length-1;i++) 8            { 9                  //每一趟需要比較次數10                  for(int j=0,j<arr.Length-i-1;j++)11                  {12                      //升序排序13                       if(arr[j]>arr[j+1])14                       {15                                temp=arr[j];//將較大的變數儲存在臨時變數16                                arr[j]=arr[j+1];17                                arr[j+1]=temp;18                        }   19                  }20             }21          22      }23 }

2.直接插入排序(InsertionSort)

public Class SortDemo{      public void InsertionSort(int[] arr)      {             int temp=0;             //遍曆待插入的數(從第二位開始)             for(int i=1;i<arr.Length;i++)             {                     int j=i-1;//(j為已排序的待插入的位置序號)                     //若已排序的數大於待插入數,則往後移一位                     while(j>=0&&arr[j]>arr[i])                     {                            arr[j+1]=arr[j];                            j--;                      }                     arr[j+1]=arr[i];//將待插入的數放入插入位置              }      }}

3.選擇排序(SelectionSort)

public void SelectionSort(int[] arr) {
int temp; for(int i=0;i<arr.Length-1;i++)
{
int minVal=arr[i];
int minIndex=i;
for(int j=i+1;j<arr.Length;j++)
{
if(minVal>arr[j])
{
minVal=arr[j];
minIndex=j;
}
}
temp=arr[i];
arr[i]=minVal;
arr[minIndex]=temp;
} }}

 

面試常考各類排序演算法總結.(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.