準備面試前複習一下各種排序算法
只給出核心代碼,其餘自行補充。
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;
}
}
}
- 希爾排序:
3. - 簡單選擇排序:
- 堆排序:
- 冒泡排序:
常規的冒泡排序:
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;
}
}
}
- 快速排序:
- 歸併排序:
- 基數排序: