首页 > 代码库 > 排序算法练习

排序算法练习

一、直接插入排序

 

 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

 

排序算法练习