zoukankan      html  css  js  c++  java
  • 降序和升序 的区别,就在于这个

    原文发布时间为:2009-03-18 —— 来源于本人的百度文章 [由搬家工具导入]

    原理:

    升序和降序 只是 大于 和 小于 号的区别。

    比如:

    if(a[j] > a[j+1])   swap(a[j],a[j+1]) 为升序

    if(a[j] < a[j+1])   swap(a[j],a[j+1]) 为降序

    那怎样做到用同一个方法呢。那么就要乘以一个值order,order为1时为升序,为-1时为降序,就可以写成如下形式:

    if(a[j]*order > a[j+1]*order)   swap(a[j],a[j+1])    order为1时为升序,为-1时为降序

    例子:

    using System;

    namespace sorts
    {
       public class Class1
        {
           public static void Main()//将数组的升序和降序排列分别储存在两个新数组中
           {
               int[] a = new int[] { 3, 4, 2, 8, 4, 5, 6 };
               int[] b = new int[a.Length];
               int[] c = new int[a.Length];

               //for (int i = 0; i < a.Length; i++)
               //{
               //    int j = i;
               //    int k = i;
               //    int temp = a[i];
               //    while (j > 0 && b[j - 1] > temp)//升序
               //    {
               //        b[j] = b[j - 1];
               //        j--;
               //    }
               //    while (k > 0 && c[k - 1] < temp)//降序
               //    {
               //        c[k] = c[k - 1];
               //        k--;
               //    }
               //    c[k] = b[j] = temp;
               //}

               InsertSort(a,b, 1);
               InsertSort(a,c, -1);
               Output(a);
               Output(b);
               Output(c);
               Console.ReadLine();
           }

           public static void Output(int[] arr)
           {
               for (int i = 0; i < arr.Length; i++)
                   Console.Write("{0} ", arr[i]);
               Console.WriteLine();
           }

           public static void InsertSort(int[] oldArr, int[] newArr, int order)
           {

               for (int i = 0; i < oldArr.Length; i++)
               {
                   int j = i;
                   int temp = oldArr[i];
                   while (j > 0 && newArr[j - 1] * order > temp * order)
                   {
                       newArr[j] = newArr[j - 1];
                       j--;
                   }
                   newArr[j] = temp;
               }
           }
       }

    }

  • 相关阅读:
    了解windows下的npm
    “jupyter notebook 不能导入python库但是终端上可以实现”的问题的解决
    本地创建的jupyter notebook 无法连接本地环境(即不能运行代码)
    win10 + ubuntu 下右键新建md文件(转载)
    LeetCode刷题2
    【入门】离散化
    【10.5NOIP普及模拟】sum
    【10.5NOIP普及模拟】sort
    【2020.02.01NOIP普及模拟4】怪兽
    [图论]最小花费
  • 原文地址:https://www.cnblogs.com/handboy/p/7153257.html
Copyright © 2011-2022 走看看