二分法直接插入排序
前面写了个直接插入排序的算法,后来看了看书还有一个二分法直接插入排序,看了看算法思想,拿起纸笔开始行动。一个字晕,思路很清楚,但是上机运行就是不对。搞了老半天终于出来,代码如下。这个算法的思想是这样的,一部分和直接插入排序是一样的,(k1,k2,k3..ki-1)ki...kn 也是把ki插到k1~ki-1的已排好序的队列里,不同的是直接插入排序是一个一个的向前比较来确定插入位址并且完成元素的向后移动,而二分法直接插入排序是先利用二分法来确定插入位置,然后再统一把元素向后移动,算法的时间复杂度是N^2. 算法这东西是最有意思的,相对来说也是最不太好写的,如果能用纸笔把算法学的完美就是牛人了,实际上我发现是很难做到,努力中!
[C#]
[C#]
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 int[] a = { 7, 2, 1, 6, 13,21, 8, 4, 33, 26 };
6 PrintArray(a);
7 BinaryInsertSort(a);
8 PrintArray(a);
9 }
10
11 private static void BinaryInsertSort(int[] a)
12 {
13 int low = 0;
14 int high = 0;
15 int mid = 0;
16 int current = 0;
17 for (int i = 1; i < a.Length; i++)
18 {
19 current = a[i];
20 low = 0;
21 high = i - 1;
22 while (low <= high)
23 {
24 mid = (low + high) / 2;
25 if (a[i] < a[mid])
26 {
27 high = mid - 1;
28 }
29 else
30 {
31 low = mid + 1;
32 }
33 }
34 for (int j = i - 1; j >= low; j--)
35 {
36 a[j + 1] = a[j];
37 }
38 a[low] = current;
39 }
40 }
41
42 private static void PrintArray(int[] array)
43 {
44 string result = string.Empty;
45 for (int i = 0; i < array.Length; i++)
46 {
47 result += array[i].ToString() + " ";
48 }
49 Console.WriteLine(result.Trim());
50 }
51 }
2 {
3 static void Main(string[] args)
4 {
5 int[] a = { 7, 2, 1, 6, 13,21, 8, 4, 33, 26 };
6 PrintArray(a);
7 BinaryInsertSort(a);
8 PrintArray(a);
9 }
10
11 private static void BinaryInsertSort(int[] a)
12 {
13 int low = 0;
14 int high = 0;
15 int mid = 0;
16 int current = 0;
17 for (int i = 1; i < a.Length; i++)
18 {
19 current = a[i];
20 low = 0;
21 high = i - 1;
22 while (low <= high)
23 {
24 mid = (low + high) / 2;
25 if (a[i] < a[mid])
26 {
27 high = mid - 1;
28 }
29 else
30 {
31 low = mid + 1;
32 }
33 }
34 for (int j = i - 1; j >= low; j--)
35 {
36 a[j + 1] = a[j];
37 }
38 a[low] = current;
39 }
40 }
41
42 private static void PrintArray(int[] array)
43 {
44 string result = string.Empty;
45 for (int i = 0; i < array.Length; i++)
46 {
47 result += array[i].ToString() + " ";
48 }
49 Console.WriteLine(result.Trim());
50 }
51 }