C#经典四种算法

  • 冒泡排序:
 #region 冒泡排序
 static void Main(string[] args)
 {
     int[] list = new int[] { 1, 90, 23, 54, 12, 59, 59, 95, 76, 83 };
     int num = list.Length - 1;
     for (int i = 0; i < num; i++)
     {
         for (int j = 0; j < num - i; j++)
         {
             if (list[j] > list[j + 1])
             {
                 int temp = list[j];
                 list[j] = list[j + 1];
                 list[j + 1] = temp;
             }
         }
     }
     for (int i = 0; i < list.Length; i++)
     {
         Console.WriteLine(list[i]);
     }
     Console.ReadKey();
 }
 #endregion
  • 选择排序
#region 选择排序
public static void Main(string[] args)
{
    int[] ints = new[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };
    SortTest st = new SortTest();
    st.Sort(ints);
    for (int m = 0; m <= 13; m++)
        Console.WriteLine("{0}", ints[m]);
}

public class SortTest
{
    private int min;
    public void Sort(int[] list)
    {
        for (int i = 0; i < list.Length; ++i)
        {
            min = i;
            for (int j = i + 1; j < list.Length; ++j)
            {
                if (list[j] < list[min])
                    min = j;
            }
            int t = list[min];
            list[min] = list[i];
            list[i] = t;
        }
    }
}
#endregion
  • 插入排序
#region 插入排序
public static void Main(string[] args)
{
    int[] iArrary = new int[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };
    SortTest st = new SortTest();
    st.Sort(iArrary);
    for (int i = 0; i <= 13; i++)
        Console.WriteLine("{0}", iArrary[i]);
    Console.ReadKey();
}
public class SortTest
{
    public void Sort(int[] list)
    {
        for (int i = 0; i < list.Length; ++i)
        {
            int t = list[i];
            int j = i;
            while ((j > 0) && (list[j - 1] > t))
            {
                list[j] = list[j - 1];
                --j;
            }
            list[j] = t;
        }
    }
}
#endregion
  • 希尔排序
#region 希尔排序
public static void Main(string[] args)
{
    int[] iArrary = new int[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };
    SortTest st = new SortTest();
    st.Sort(iArrary);
    for (int i = 0; i <= 13; i++)
        Console.WriteLine("{0}", iArrary[i]);
    Console.ReadKey();
}
public class SortTest
{
    public void Sort(int[] list)
    {
        int inc;
        for (inc = 1; inc < list.Length / 9; inc = 3 * inc + 1) ;
        for (; inc > 0; inc /= 3)
        {
            for (int i = inc + 1; i <= list.Length; i += inc)
            {
                int t = list[i - 1];
                int j = i;
                while ((j > inc) && list[j - inc - 1] > t)
                {
                    list[j - 1] = list[j - inc - 1];
                    j -= inc;
                }
                list[j - 1] = t;
            }
        }
    }
}
#endregion

 

posted @ 2024-03-06 14:53  左耳*  阅读(68)  评论(0编辑  收藏  举报