冒泡排序[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
此外,常用的還有選擇排序和插入排序,我會在後面的文檔中做介紹。