第2章答案

2.1插入排序算法:c#语言实现

 1 static void Main(string[] args)
 2 {
 3     Console.WriteLine("请输入要排序数组的长度:");
 4     int length=int.Parse(Console.ReadLine());
 5     int[] insertSort=new int[length];
 6     Console.WriteLine("请输入要排序的数:");
 7     for (int i = 0; i < length;i++ )
 8     {
 9          insertSort[i] = int.Parse(Console.ReadLine());
10     }
11     //开始排序:
12     int k = 0,key = 0;
13     for (int j = 1; j < length;j++ )
14     {
15          key=insertSort[j];
16          k = j - 1;
17          while (k>=0 && insertSort[k]>key)
18          {
19               insertSort[k + 1] = insertSort[k];
20               k = k - 1;
21               insertSort[k + 1] = key;
22           }
23       }
24       Console.WriteLine("排序结果为:");
25       for (int i = 0; i < length;i++ )
26       {
27           Console.WriteLine(insertSort[i]);
28       }
29       Console.ReadKey();
30}

运行结果:

初学者不要感觉简单,一带而过要真正的理解过程,请仔细体会第17行代码的while语句,最好是设断点一步一步走一遍就清晰了。

2.1-2 按非升序排序

和非降序的没什么区别,将insertSort[k]>key改写成insertSort[k]<key即可!

posted @ 2013-05-27 20:59  夜曲984  阅读(146)  评论(0编辑  收藏  举报