C#插入排序

  1. using System;
  2. namespace InsertionSort
  3. {
  4.     /// <summary>
  5.     /// 插入排序
  6.     /// </summary>
  7.     public class InsertionSort
  8.     {
  9.         public void Sort(int[] list)
  10.         {
  11.             for (int i = 1; i < list.Length; i++)
  12.             {
  13.                 int temp = list[i];
  14.                 int j = i;
  15.                 while ((j > 0) && (list[j - 1] > temp))
  16.                 {
  17.                     list[j] = list[j - 1];
  18.                     j--;
  19.                 }
  20.                 list[j] = temp;
  21.             }
  22.         }
  23.         static void Main(string[] args)
  24.         {
  25.             int[] test = new int[] { 1, 6, 3, 8, 11, 43, 0, 3, 57 };
  26.             InsertionSort its = new InsertionSort();
  27.             its.Sort(test);
  28.             for (int i = 0; i < test.Length - 1; i++)
  29.             {
  30.                 Console.WriteLine("{0}", test[i]);
  31.             }
  32.             Console.ReadKey();
  33.         }
  34.     }
  35. }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章