依次比较相邻的两个数,将小数放在前面,大数放在后面。
第1趟:
首先比较第1个和第2个数,将小数放前,大数放后。然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。至此第一趟结束,将最大的数放到了最后。
第2趟:
仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),将小数放前,大数放后,一直比较到倒数第二个数(倒数第一的位置上已经是最大的),第二趟结束,在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。
如此下去,重复以上过程,直至最终完成排序。
由于在排序过程中总是小数往前放,大数往后放,相当于气泡往上升,所以称作冒泡排序。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Collections;
-
- namespace 冒泡排序算法
- {
-
-
-
-
- class Program
- {
- static void Main(string[] args)
- {
- int[] array = {10,6,1,3,4,2,5,9,7,8};
- BubbleSort bs = new BubbleSort();
- bs.Maopao(array);
- for (int i = 0; i < array.Length; i++)
- {
- Console.Write("{0} ", array[i].ToString());
- }
- Console.ReadLine();
- }
- }
- public class BubbleSort
- {
- public void Maopao(int[] items)
- {
- for (int i = 0; i < items.Length; i++)
- {
- bool flag = false;
- for (int j = 0; j < items.Length - 1 - i; j++)
- {
- if (items[j] > items[j + 1])
- {
- int temp = items[j];
- items[j] = items[j + 1];
- items[j + 1] = temp;
- flag = true;
- }
- }
- if (flag == false)
- {
- break;
- }
- }
-
- }
-
- }
快速排序算法
using System;
2

3

public class Sort
4
{
5
public class Quick_Sort
6
{
7
private static int QuickSort_Once(int[] _pnArray, int _pnLow, int _pnHigh)
8
{
9
int nPivot = _pnArray[_pnLow]; //将首元素作为枢轴
10
int i = _pnLow, j = _pnHigh;
11
12
while (i < j)
13
{
14
//从右到左,寻找首个小于nPivot的元素
15
while (_pnArray[j] >= nPivot && i<j) j--;
16
//执行到此,j已指向从右端起首个小于nPivot的元素
17
//执行替换
18
_pnArray[i] = _pnArray[j];
19
//从左到右,寻找首个大于nPivot的元素
20
while (_pnArray[i] <= nPivot && i<j) i++;
21
//执行到此,i已指向从左端起首个大于nPivot的元素
22
//执行替换
23
_pnArray[j] = _pnArray[i];
24
}
25
26
//推出while循环,执行至此,必定是i=j的情况
27
//i(或j)指向的即是枢轴的位置,定位该趟排序的枢轴并将该位置返回
28
_pnArray[i] = nPivot;
29
return i;
30
}
31
32
private static void QuickSort(int[] _pnArray, int _pnLow, int _pnHigh)
33
{
34
if (_pnLow >= _pnHigh) return;
35
36
int _nPivotIndex = QuickSort_Once(_pnArray, _pnLow, _pnHigh);
37
//对枢轴的左端进行排序
38
QuickSort(_pnArray, _pnLow, _nPivotIndex-1);
39
//对枢轴的右端进行排序
40
QuickSort(_pnArray, _nPivotIndex + 1,_pnHigh);
41
}
42
43
public static void Main()
44
{
45
Console.WriteLine("请输入待排序数列(以\",\"分割):");
46
string _s = Console.ReadLine();
47
string[] _sArray = _s.Split(",".ToCharArray());
48
int _nLength = _sArray.Length;
49
int[] _nArray = new int[_nLength];
50
for (int i = 0; i < _nLength; i++)
51
{
52
_nArray[i] = Convert.ToInt32(_sArray[i]);
53
}
54
QuickSort(_nArray, 0, _nLength-1);
55
Console.WriteLine("排序后的数列为:");
56
foreach (int _n in _nArray)
57
{
58
Console.WriteLine(_n.ToString());
59
}
60
}
61
}
62
}
63