1 /// <summary> 2 /// 折半排序 3 /// </summary> 4 /// <param name="sqList"></param> 5 public void BInsertSort(List<int> sqList) 6 { 7 for (int i =1; i < sqList.Count; i++) 8 { 9 int key = sqList[i]; 10 int low = 0, high = i - 1; 11 while (low < high) 12 { 13 int mid= (low + high) / 2; 14 if (key <sqList[mid]) 15 high = mid - 1; 16 else 17 low = mid + 1; 18 } 19 20 for (int j = i - 1; j >=high + 1; j--) 21 { 22 sqList[j + 1] = sqList[j]; 23 } 24 sqList[high +1] = key; 25 } 26 } 27 28 29 30 31 32 33 34 static void Main(string[] args) 35 { 36 List<int> sq = new List<int>{ 3, 4, 51, 8, 5, 9, 2, 34,6,44,33 }; 37 BinaryInsertioSort bis = new BinaryInsertioSort(); 38 bis.BInsertSort(sq); 39 foreach (var x in sq) 40 { 41 Console.WriteLine("{0}" ,x); 42 } 43 Console.ReadKey(); 44 }
建议看看这篇文章:排序>>>插入排序>>>折半插入排序
问个问题:while(low<high) 和while(low<=high)结果差别这么大?
且 for(int j=i-1;j>=high+1;j--)与for(int j=i-1;j>=low;j--)
这里的区别在哪里?
细节啊,细节决定成败!!!