直接插入排序

简单?谁说的,哥们儿好久不搞这东西,突然上手,我这个晕呀!想了老半天才回忆起直接插入排序的算法思想。有了思想去写程序,发现真的生疏了花了半个多小时才写出来,代码在下面了。说实话,直接插入排序不常用到,其时间复杂度为O(n^2),思想是:(k1,k2,k3,ki-1)Ki...Kn,把Ki插入到前面(k1~ki-1)这个已排好序的队列里,Ki的插入方法为:把Ki与Ki-1项比较,如Ki<Ki-1则交换,然后i--,继续向前比较,直到Ki>=Ki-1为止。

[C#]

 1    class Program
 2    {
 3        static void Main(string[] args)
 4        {
 5            int[] a = 72162113843326 };
 6            PrintArray(a);
 7            InsertSort(a);
 8            PrintArray(a);
 9        }

10
11        private static void InsertSort(int[] array)
12        {
13            for (int i = 1; i < array.Length; i++)
14            {
15                int temp = array[i];
16                int j = i - 1;
17                while (j >= 0 && array[j] > array[j+1])
18                {
19                    array[j+1= array[j];
20                    array[j] = temp;
21                    j--;
22                }

23            }

24        }

25
26        private static void PrintArray(int[] array)
27        {
28            string result = string.Empty;
29            for (int i = 0; i < array.Length; i++)
30            {
31                result += array[i].ToString() + " ";
32            }

33            Console.WriteLine(result.Trim());
34        }

35    }

 

posted @ 2009-09-10 13:55  烟鬼  阅读(373)  评论(0编辑  收藏  举报