使用C#定义一个数组让他插入排序

            int[] arr = {
    
     30, 12, 56, 78, 12125, 56, 44, 212, 45, 787, 21, 22, 56, 65 };  //待排序数组
            for (int i = 1; i < arr.Length; i++)
            {
    
    
                int a = arr[i];  //首先记住这个预备要插入的数
                int b = i - 1; //找出它前一个数的下标(等下 准备插入的数 要跟这个数做比较)

                //如果这个条件满足,说明,我们还没有找到适当的位置
                while (b >= 0 && a > arr[b])   //这里小于是升序,大于是降序
                {
    
    
                    arr[b + 1] = arr[b];   //同时把比插入数要大的数往后移
                    b--;      //指针继续往后移,等下插入的数也要跟这个指针指向的数做比较         
                }
                arr[b + 1] = a;
            }
            foreach (int item in arr)
                Console.WriteLine(item);

输出结果为
七月

猜你喜欢

转载自blog.csdn.net/qq_28058231/article/details/108851234