常見排序算法

準備面試前複習一下各種排序算法

只給出核心代碼,其餘自行補充。
1. 插入排序:

static void insertion_sort(int [] unsorted)
{
    for(int i = 1; i < unsorted.Length; i++)
    {
        if(unsorted[i -1] > unsorted [i])
        {
            int temp = unsorted[i];
            int j = i;
            while( j> 0 && temp < unsorted [j-1])
            {
                unsorted[j] = unsorted[j-1];
                j--;
            }
            unsorted[j] = temp;
        }
    }
}
  1. 希爾排序:
    3.
  2. 簡單選擇排序:
  3. 堆排序:
  4. 冒泡排序:
    常規的冒泡排序:
static void bublleSort(int [] unsorted )
{
    for(int i =0; i < unsorted.Length; i++)
    {
        for(int j = 0; j < unsorted.Length-i; j++)
        {
            if(a[j] > a[j+1] )
            {
                int temp = a[j];
                a[j] = a[j +1];
                a[j+1] = temp;
            }
        }
    }
}

加入標誌性變量pos:

static void Bubble_1( int [] unsorted)
{
    i = unsorted.Length;
    while( i >0)
    {
        int pos=0;
        for(int j= 0; j <i; j++)
        {
            if(unsorted[j] > unsorted[j + 1])
            {
                pos = j;
                int temp =unsorted[j];
                unsorted[j] = unsorted[j+1];
                unsorted[j+1] = unsorted[j];
            }
            i = pos;
        }
    }
}
  1. 快速排序:
  2. 歸併排序:
  3. 基數排序:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章