排序算法练习

转载请注明地址:http://www.cnblogs.com/Vincentblogs/p/4083028.html

QQ群:346738352 Unity技术交流群,讲纯粹的技术。 

一、直接插入排序

 实现原理:在一组无序的数组中,以每个数插入到前面的数对比,逐个对比交换。

 1     class Program
 2     {
 3         /// <summary>
 4         /// swap two number
 5         /// </summary>
 6         /// <param name="a"></param>
 7         /// <param name="b"></param>
 8         static void Swap(ref int a, ref int b)
 9         {
10             int temp = a;
11             a = b;
12             b = temp;
13         }
14         static void Main(string[] args)
15         {
16             Console.WriteLine("Algorithm test first!\nInsert Sort Start....");
17             int[] arr = new int[] { 2, 3, 1, 0, 5 };
18 
19             for (int i = 0; i < arr.Length; i++)
20             {
21                 for (int j = i + 1; j >= 1; j--)
22                 {
23                     if (j >= arr.Length)
24                         break;
25                     if (arr[j] < arr[j - 1])
26                     {
27                         Swap(ref arr[j], ref arr[j-1]);
28                     }
29                 }
30             }
31 
32             foreach(int i in arr)
33             {
34                 Console.Write(i + " ");
35             }
36 
37         }
38     }
View Code

 

posted @ 2014-10-31 13:59  Think_From_Code  阅读(135)  评论(0编辑  收藏  举报