C#冒泡排序[改良後]

來源:互聯網
上載者:User
冒泡排序[BubbleSort]
一。基本思想
      兩兩比較待排序資料元素的大小,發現兩個資料元素的次序相反時即進行交換,直到沒有反序的資料元素為止。
二。排序過程
      設想被排序的數組R[1..N]垂直豎立,將每個資料元素看作有重量的氣泡,根據輕氣泡不能在重氣泡之下的原則,從   下往上掃描數組R,凡掃描到違反本原則的輕氣泡,就使其向上"漂浮",如此反覆進行,直至最後任何兩個氣泡都是輕者在上,重者在下為止。
三。程式碼範例Code
 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4
 5namespace bubbleSort
 6{
 7    class BubbleSort
 8    {
 9        static void Main(string[] args)
10        {
11            int[] a = { 2,5,3,7,10,9};
12            Console.WriteLine("Soct Result is :");
13            Sort(a);
14            for (int k = 0; k < a.Length; k++)
15            {
16                Console.WriteLine(a[k]);
17            }
18        }
19
20        private static void Sort(int[] arr)
21        {
22            int i, j, n=0, temp=0;
23            n = arr.Length;
24            bool f = true; //記錄一狀態
25            for (i = 0; i < n - 1; i++)
26            {
27                f = true;
28                for (j = n-1; j > i; j--)
29                {
30                    if (arr[j] <arr[j - 1])
31                    {
32                        temp = arr[j];
33                        arr[j] = arr[j-1];
34                        arr[j - 1] = temp;
35                        f = false; //如順序進行調整,狀態也發生變化
36                    }
37                }
38                if(f ==true) //如數組內容本身就是一個順序排序的,內部比較一次直接跳出迴圈
39                {
40                    break;
41                }
42            }
43        }
44    }
45}
46

此外,常用的還有選擇排序和插入排序,我會在後面的文檔中做介紹。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.