程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#遍歷排序的方法

C#遍歷排序的方法

編輯:C#入門知識

今天來介紹一下C#中遍歷排序的方法,今天就介紹下冒泡法,直接插入法和選擇排序法。

1、冒泡法

題目:使用冒泡法對數組中的元素從小到大進行排序。

方法一:

int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
            foreach (int m in arr)
            {
                Console.Write(m + " ");
            }               
            Console.WriteLine();
            int j, temp;
            for (int i = 0; i < arr.Length - 1; i++)
            {
                j = i + 1;
                id:
                if (arr[i] > arr[j])
                {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    goto id;
                }
                else
                {
                    if (j < arr.Length - 1)
                    {
                        j++;
                        goto id;
                    }
                }
            }
            foreach (int n in arr)
            {
                Console.Write(n + " ");
            }      
            Console.WriteLine();
            Console.ReadLine();

方法二:

            int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
            int i, j, temp;
            bool done = false;
            j = 1;
            while ((j < arr.Length) && (!done))
            {
                done = true;
                for (i = 0; i < arr.Length - j; i++)
                {
                    if (arr[i] > arr[i + 1])
                    {
                        done = false;
                        temp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = temp;
                    }
                }
                j++;

            }
            foreach (int n in arr)
            {
                Console.Write(n + "--");
            }
            Console.WriteLine();
            Console.ReadLine();

2、插入排序法

int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
            foreach (int n in arr)
                Console.Write("{0}", n + " ");
            Console.WriteLine();
            for (int i = 0; i < 6; ++i)
            {
                int temp = arr[i];
                int j = i;
                while ((j > 0) && (arr[j - 1] > temp))
                {
                    arr[j] = arr[j - 1];
       &nb

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved