// 冒泡排序:稳定,时间复杂度 O(n^2)
void Bub_Sort(int *array, int n)
{
int i, j;
for(i = 0; i < n - 1; i++)
for(j = 0; j < n - 1 - i; j++)
if(array[j] > array[j+1])
{
int temp;
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
return;
}
// 选择排序:不稳定,时间复杂度 O(n^2)
void Sel_Sort(int *array, int n)
{
int i, j, k;
for(i = 0; i < n - 1; i++)
{
k = i;
for(j = i + 1; j < n; j++)
if(array[k] > array[j])
k = j;
if(k != i)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
return;
}
// 插入排序:稳定,时间复杂度 O(n^2)
void Ins_Sort(int *array, int n)
{
int i, j, key;
for(i = 1; i < n; i++)
{
j = i - 1;
key = array[i];
while(j >= 0 && array[j] > key)
{
array[j+1] = array[j];
j--;
}
array[j+1] = key;
}
return;
}
// 快速排序:不稳定,时间复杂度 最理想 O(nlogn) 最差时间O(n^2)
void Qui_Sort(int *array, int n)
{
int i, j;
int val;
i = 0;
j = n - 1;
val = array[0];
if(n > 1)
{
while(i < j)
{
for(; j > i; j--)
if(array[j] < val)
{
array[i++] = array[j];
break;
}
for(; i < j; i++)
if(array[i] > val)
{
array[j--] = array[i];
break;
}
}
array[i] = val;
Qui_Sort(array, i);
Qui_Sort(array + i + 1, n - i - 1);
}
return;
}
// 堆排序:不稳定,时间复杂度 O(nlog n)
void HeapAdjust(int *array, int i, int n)
{
int nChild;
for(; 2 * i + 1 < n; i = nChild)
{
nChild = 2 * i + 1;
if(nChild < n - 1 && array[nChild] < array[nChild+1])
nChild++;
if(array[i] < array[nChild])
{
int temp;
temp = array[i];
array[i] = array[nChild];
array[nChild] = temp;
}
else
break;
}
return;
}
void Hea_Sort(int *array, int n)
{
int i;
for(i = n / 2 - 1; i >= 0; i--)
HeapAdjust(array, i, n);
for(i = n - 1; i > 0; i--)
{
int temp;
temp = array[0];
array[0] = array[i];
array[i] = temp;
HeapAdjust(array, 0, i);
}
return;
}
// 归并排序:稳定,时间复杂度 O(nlog n)
void mergearray(int *array, int first, int mid, int last, int *p)
{
int i, j, m, n, k;
i = first;
j = mid + 1;
m = mid;
n = last;
k = 0;
while(i <= m && j <= n)
{
if(array[i] <= array[j])
p[k++] = array[i++];
else
p[k++] = array[j++];
}
while(i <= m)
p[k++] = array[i++];
while(j <= n)
p[k++] = array[j++];
for(i = 0; i < k; i++)
array[first+i] = p[i];
return;
}
void mergesort(int *array, int first, int last, int *p)
{
int mid;
if(first < last)
{
mid = (first + last) / 2;
mergesort(array, first, mid, p);
mergesort(array, mid + 1, last, p);
mergearray(array, first, mid, last, p);
}
return;
}
void Mer_Sort(int *array, int n)
{
int *p = NULL;
p = (int *)malloc(sizeof(int) * n);
mergesort(array, 0, n - 1, p);
free(p);
return;
}