C++、C#、java演算法學習日記04----二分插入排序
經過上幾篇對排序演算法的瞭解,我們發現,所謂的排序也就是確定一個數組中每個元素的位置,然後對號入座,其過程也就是找到該元素的位置。確定位置,使用二分法可以達到很高的效率,我們將他應用到插入排序中就算是對上篇中排序的一種最佳化,能提高效率。
基本思想:
與上篇中的插入排序類似分已排序和未排序部分,然後將未排序 部分元素逐個插入,但是插入的過程不同,需要每次求一個 中間位置,和中間位置元素比較大小,然後根據大小情況,將高位 左移或者將低位右移,再求中間元素比較,直到找到合適位置 (也就是說使用二分法確定插入位置)後 將其部分元素後移為待插入元素騰出空間,再插入該序列即可。
C++執行個體:
#includeusing namespace std;void HalfSort(int *array,int Length){//定義最低,最高,中間值,待插入資料,插入位置int low,high,middle,temp,index,i,j;for(i=1;itemp) //與頭尾相比較如果沒在範圍類省略迴圈 { while(low<=high) //二分法尋找插入位置{ middle=(low+high)/2; if(array[middle]>temp) { high=middle-1; } else low=middle+1;}//最後確定位置indexindex=low; } if(array[0]>=temp) //如果比第一個元素還小就直接插到第一個位置 { index=0;} if(array[i-1]<=temp) //如果比最後一個元素還大直接插到最後一個位置 { index=i;} //向後移位騰出插入空間 for(j=i-1;j>=index;j--) { array[j+1]=array[j];} array[index]=temp; //插入}//輸出for(i=0;i
C#執行個體:using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace HalfSort2{ class Sort { public void halfSort(int[] array) { int low,high,middle,temp,index,i; for (i = 1; i < array.Length; i++) { low = 0; high = i - 1; temp = array[i]; index = i; if (array[0] < temp && array[i - 1] > temp) { while (low <= high) //二分法尋找插入位置 { middle = (low + high) / 2; if (array[middle] > temp) { high = middle - 1; } else low = middle + 1; } index = low; } if (array[0] >= temp) //如果比第一個元素還小就直接插到第一個位置 { index = 0; } if (array[i - 1] <= temp) //如果比最後一個元素還大直接插到最後一個位置 { index = i; } //向後移位騰出插入空間 for (int j = i - 1; j >= index; j--) { array[j + 1] = array[j]; } array[index] = temp; //插入 } foreach (int j in array) { Console.Write(j + ); } Console.WriteLine(); } static void Main(string[] args) { int[] array = new int[] {63,4,24,1,3,15}; Sort sorter = new Sort(); sorter.halfSort(array); } }}
以上結果為:
java執行個體:package Sort;public class Sort {public void halfsort(int[] array){int low,high,middle,temp,index,i;for(i=1;itemp){ while(low<=high){ middle=(low+high)/2; if(array[middle]>temp){ high=middle-1; } else{ low=middle+1; } } index=low; } if(array[0]>=temp){ index=0; } if(array[i-1]<=temp){ index=i; } for(int j =i-1;j>=index;j--){ array[j+1]=array[j]; } array[index]=temp;}for(int j:array){ System.out.print(j+ ); }}public static void main(String[] args) {int[] array = new int[]{63,4,24,1,3,15};Sort sorter = new Sort();sorter.halfsort(array);}}
結果:
其實關於二分法排序,我查閱資料的時候代碼中並沒有 if(array[0]temp) ,if(array[0]>=temp),if(array[i-1]<=temp) 這樣的判斷語句,這是我自己加上的,因為如果沒有這些判斷語句的話,當讓你排序的數列已經是有序數列的時候程式還是會經曆一些不必要的迴圈,反倒不如上一篇中的直接插入排序了。