List<int> list = new List<int> { 33, 22, 1, 7, 66, 48, 95, 93, 92, 91, 46 };
        #region 冒泡排序
        public void BubbleSort()
        {
            for (int i = 0; i < list.Count; i++)
            {
                for (int j = i; j < list.Count; j++)
                {
                    if (list[i] > list[j])
                    {
                        int tmp = list[j];
                        list[j] = list[i];
                        list[i] = tmp;
                    }
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
        }
        #endregion

        #region 选择排序

//基本思想  每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
        public void SelectionSort()
        {

            for (int i = 0; i < list.Count; i++)
            {
                int minIndex = i;
                for (int j = i + 1; j < list.Count; j++)
                {
                    if (list[i] > list[j]) minIndex = j;
                }

                if(minIndex != i)
                {
                    int tmp = list[minIndex];
                    list[minIndex] = list[i];
                    list[i] = tmp;
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
        }

        #endregion

  #region 插入排序

C# 冒泡排序 选择排序 与 插入排序
        public void InsertSort()
        {
            for (int i = 1; i < list.Count; i++)
            {
                for (int j = i - 1; j >= 0; j--)
                {
                    if (list[i] < list[j] && j - 1 >= 0 && list[i]>list[j-1])
                    {
                        int tmp = list[i];
                        list[i] = list[j];
                        list[j] = tmp;
                    }
                }
            }
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }
        }
        #endregion

相关文章:

  • 2021-07-13
  • 2021-09-13
  • 2022-12-23
  • 2021-09-07
  • 2021-11-02
  • 2021-05-24
  • 2021-08-11
猜你喜欢
  • 2021-08-08
  • 2021-10-07
相关资源
相似解决方案