简述
- 假设按照索引越大元素越大的顺序排列
- 对于一个待排序的序列,有i、j两个下标。
- i 用来标记序列中还未有序的部分的当前下标(即只会遍历无序部分)。
- j 用来遍历 i~Length-2部分(这部分已经为相对有序序列)并指向bubble ,如果临近的下一个元素比bubble大则两者交换(即bubble上升了),此时下标自增1,于是仍指向bubble,否则该bubble已经在相对有序序列中处于正确的相对位置而不需要上升。
- 每次冒泡排序的 i 自增1,使得该元素(bubble)确定在相对有序序列中的相对位置。
特点
- 每次元素交换会立即使得元素被放到正确的位置上,如果某个元素位于正确的最终位置上,则它不会被移动。
- 如果序列中位于正确位置的元素越多,那么该序列用选择排序消耗的时间越小。
选择排序
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main(string[] args)
{
int[] array = { 30, 12, 56, 78, 12125, 56, 44, 212, 45, 787, 21, 22, 56, 65 };
BubbleSort(array);
foreach (int item in array)
Console.WriteLine(item);
}
private static void BubbleSort(int[] array)
{
for(int i = array.Length-2; i >= 0; i--)
{
for(int j = i; j <= array.Length-2; j++)
{
if(array[j] > array[j+1])
{
Swap(ref array[j], ref array[j+1]);
}
}
}
}
private static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}
执行结果:
12
21
22
30
44
45
56
56
56
65
78
212
787
12125