三个基本排序算法执行效率比较（冒泡排序，选择排序和插入排序）

1、冒泡算法。

public class Sorting
{
public void BubbleSorting()
{
int[] arr = new int[10];
Random rd = new Random(100);
for (int i = 0; i < arr.Length; i++)
{
arr[i] = rd.Next(1, 100);
}
Console.WriteLine("Init array:");
Print(arr);
Console.WriteLine("Sorting:");
for (int i = arr.Length - 1; i >= 1; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
Swap(ref arr[j], ref arr[j + 1]);
}
}

Print(arr);
}
Console.WriteLine("Sort Result:");
Print(arr);
}

void Swap(ref int a, ref int b)
{
var temp = a;
a = b;
b = temp;
}
void Print(int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write("" + list[i]);
} 
        Console.WriteLine();
}
}

2、选择排序

public void SelectionSort()
{
int[] arr = InitArray(10);
int length = 10;
Console.WriteLine("Sorting:");
for (int i = 0; i < length; i++)
{
int min = i;
for (int j = i + 1; j < length; j++)
{
if (arr[min] > arr[j]) min = j;
}
Swap(ref arr[i], ref arr[min]);
Print(arr);
}
Console.WriteLine("Sort Result:");
Print(arr);
}

3、插入排序

public void InsertionSort()
{
int[] arr = InitArray(10);
int length = 10;
Console.WriteLine("Sorting:");
for (int i = 1; i < length; i++)
{
int temp = arr[i];
int inner=i;
while (inner > 0 && arr[inner - 1] >= temp)
{
arr[inner] = arr[inner - 1];
inner--;
}
arr[inner] = temp;
Print(arr);
}
Console.WriteLine("Sort Result:");
Print(arr);
}

4、三种算法的效率

static void TestSorting(int size)
{
Sorting sort = new Sorting();
Stopwatch watch = new Stopwatch();
watch.Start();
sort.BubbleAscSorting(size);
watch.Stop();
Console.WriteLine("BubbleAscSorting Time Milliseconds:" + watch.ElapsedMilliseconds);
watch.Restart();
sort.SelectionSort(size);
watch.Stop();
Console.WriteLine("SelectionSort Time Milliseconds:" + watch.ElapsedMilliseconds);
watch.Restart();
sort.InsertionSort(size);
Console.WriteLine("InsertionSort Time Milliseconds:" + watch.ElapsedMilliseconds);
}

1000个整数结果：

10000个整数结果：

100000个整数结果：

 Bubble Selection Insertion Bubble/Selection Bubble/Insertion Selection/Insertion 1000 15 4 3 3.75 5 1.333333333 10000 1342 412 283 3.257281553 4.74204947 1.455830389 100000 125212 40794 27570 3.069372947 4.541603192 1.479651795 Avg 3.358884833 4.761217554 1.422938506

1.冒泡算法效率最低。

2.插入算法效率最高。

3.选择算法是冒泡算法的3.3倍。

4.插入算法是冒泡算法的4.7倍。

5.插入算法是选择算法的1.4陪。