標籤:開始 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#)