稳定的:
1.冒泡排序(bubble sort)
时间复杂度:最优O(N),平均和最坏O(N^2)。
冒泡排序算法的运作如下:(从后往前)
-
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
-
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
-
针对所有的元素重复以上的步骤,除了最后一个。
#include <stdio.h>
#define SIZE 8
void
bubble_sort(
int
a[],
int
n);
void
bubble_sort(
int
a[],
int
n)
{
int
i, j, temp;
for
(j = 0; j < n - 1; j++)
for
(i = 0; i < n - 1 - j; i++)
{
if
(a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
int
main()
{
int
number[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12};
int
i;
bubble_sort(number, SIZE);
for
(i = 0; i < SIZE; i++)
{
printf
(
"%d"
, number[i]);
}
printf
(
"\n"
);
}
2.鸡尾酒排序(Cocktail sort,双向的冒泡排序)
时间复杂度:若一开始大部分排序过,接近O(N),否则O(N^2);
function cocktail_sort(list, list_length)
// the first element of list has index 0
{
bottom = 0;
top = list_length - 1;
swapped =
true
;
bound = 0;
//优化循环次数,记录已经排序的边界,减少循环次数
while
(swapped)
// if no elements have been swapped, then the list is sorted
{
swapped =
false
;
for
(i = bottom; i < top; i = i + 1)
{
if
(list[i] > list[i+1])
// test whether the two elements are in the correct order
{
swap(list[i], list[i+1]);
// let the two elements change places
swapped =
true
;
bound = i;
}
}
// decreases top the because the element with the largest value in the unsorted
// part of the list is now on the position top
//top = top - 1;
top = bound;
for
(i = top; i > bottom; i = i - 1)
{
if
(list[i] < list[i-1])
{
swap(list[i], list[i-1]);
swapped =
true
;
bound = i;
}
}
// increases bottom because the element with the smallest value in the unsorted
// part of the list is now on the position bottom
//bottom = bottom + 1;
bottom = bound;
}
}
3.插入排序(insertion sort)
时间复杂度:O(N^2)
插入排序的基本思想是:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。
voidinsert_sort(
int
*array,unsignedintn)
{
inti,j;
inttemp;
for
(i=1;i<n;i++)
{
temp=*(array+i);
for
(j=i;j>0&&*(array+j-1)>temp;j--)
{
*(array+j)=*(array+j-1);
}
*(array+j)=temp;
}
}
4.桶排序(bucket sort)— O(n); 需要 O(k) 额外空间
时间复杂度:
桶排序的平均时间复杂度为线性的O(N+C),其中C=N*(logN-logM)。如果相对于同样的N,桶数量M越大,其效率越高,最好的时间复杂度达到O(N)。当然桶排序的空间复杂度为O(N+M),如果输入数据非常庞大,而桶的数量也非常多,则空间代价无疑是昂贵的。此外,桶排序是稳定的。
5.计数排序(counting sort) — O(n+k); 需要 O(n+k) 额外空间
6.合并排序(merge sort)— O(nlog n); 需要 O(n) 额外空间
7.二叉排序树排序 (Binary tree sort) — O(nlog n)期望时间; O(n^2)最坏时间; 需要 O(n) 额外空间
8.鸽巢排序(Pigeonhole sort) — O(n+k); 需要 O(k) 额外空间
9.基数排序(radix sort)— O(n·k); 需要 O(n) 额外空间
不稳定的:
1.选择排序(selection sort)— O(n^2)
2.希尔排序(shell sort)— O(nlog n) 如果使用最佳的现在版本
3.堆排序(heapsort)— O(nlog n)
4.快速排序(quicksort)— O(nlog n) 期望时间,O(n^2) 最坏情况; 对于大的、乱数列表一般相信是最快的已知排序
Introsort— O(nlog n)