1. 程式人生 > >降序和升序 的區別,就在於這個

降序和升序 的區別,就在於這個

int console emp using lda con esp ++ 升序

原文發布時間為: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;
           }
       }
   }

}

降序和升序 的區別,就在於這個