冒泡,选择,插入

   class Program
    {
        static void Main(string[] args)
        {
            int[] arr=new int[10];
            Random rnd = new Random(100);
            for (int i = 0; i <arr.Length; i++)
            {
                arr.SetValue(rnd.Next(0, 100),i);
            }
            DispalyElements(arr);
            Console.WriteLine();
            //BubbleSort(arr);
            //SelectionSort(arr);
            InsertionSort(arr);
            Console.WriteLine();
            DispalyElements(arr);
            Console.ReadKey();
        }

        public static void DispalyElements(int[] arr)
        {
            foreach (var item in arr)
            {
                Console.Write(item + "  " );
            }
        }
        public static  void BubbleSort(int[] arr)
        {
            int temp;
            for (int i = 0; i < arr.Length-1; i++)
            {
                for (int j = arr.Length - 1; j > 0;j-- )
                {
                    if (arr[j]<arr[j-1])
                    {
                        temp = arr[j];
                        arr[j] = arr[j - 1];
                        arr[j - 1] = temp;
                    }
                }
                DispalyElements(arr);
                Console.WriteLine();
            }
        }

        public static void SelectionSort(int[] arr)
        {
            int min, temp;
            for (int i = 0; i < arr.Length; i++)
            {
                min = i;
                for (int j = i+1; j < arr.Length; j++)
                {
                    if (arr[j]<arr[min])
                    {
                        min = j;
                    }
                }
                temp = arr[i];
                arr[i] = arr[min];
                arr[min] = temp;
                DispalyElements(arr);
                Console.WriteLine();
            }
        }

        public static void InsertionSort(int[] arr)
        {
            int j, temp;
            for (int i = 0; i < arr.Length; i++)
            {
                temp = arr[i];
                j = i;
                while (j>0&&arr[j-1]>=temp)
                {
                    arr[j] = arr[j - 1];
                    j--;
                }
                arr[j] = temp;
                DispalyElements(arr);
                Console.WriteLine();
            }
        }
    }
View Code
原文地址:https://www.cnblogs.com/futengsheng/p/7823762.html