1 直接插入排序
void InsertSort(int *a, int size)
{
int i, j, tmp;
for (i = 1; i < size; i++)
{
tmp = a[i];
for (j = i - 1; j >= 0; j--)
{
if (tmp < a[j])
{
a[j + 1] = a[j];
count++;
}
else
{
break;
}
}
a[j + 1] = tmp;
}
}
2 希尔排序
void ShellSort(int *a, int size)
{
int i, j, tmp, h;
for (h = size / 2; h > 0; h /= 2)
{
for (i = h; i < size; i++)
{
tmp = a[i];
for (j = i - h; j >= 0; j -= h)
{
if (tmp < a[j])
{
a[j + h] = a[j];
}
else
{
break;
}
}
a[j + h] = tmp;
}
}
}
3 冒泡排序
void BubbleSort(int *a, int size)
{
int i, j, tmp;
for (i = 0; i < size - 1; i++)
{
for (j = 0; j < size - i - 1; j++)
{
if (a[j] > a[j + 1])
{
tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
}
4 快速排序
void QuickSort(int *a, int low, int high)
{
if (low >= high)
{
return ;
}
int x = low;
int y = high;
int Index = a[x];
while (x < y)
{
while(x < y && a[y] > Index)
{
y--;
}
if (x < y)
{
a[x++] = a[y];
}
while (x < y && a[x] < Index)
{
x++;
}
if (x < y)
{
a[y--] = a[x];
}
}
a[x] = Index;
QuickSort(a, low, x - 1);
QuickSort(a, x + 1, high);
}
5选择排序
void SelectSort(int *a, int size)
{
int i, j, tmp;
int minIndex = 0;
for (i = 0; i < size - 1; i++)
{
minIndex = i;
for (j = i + 1; j < size; j++)
{
if (a[minIndex] > a[j])
{
minIndex = j;
}
}
tmp = a[minIndex];
a[minIndex] = a[i];
a[i] = tmp;
}
}
6 堆排序
void AdjustHeap(int *a, int root, int last)
{
int child = 2 * root + 1;
int tmp = a[root];
while(child <= last)
{
if (child + 1 <= last && a[child] < a[child + 1])
{
child++;
}
if (a[child] > tmp)
{
a[root] = a[child];
}
else
{
break;
}
root = child;
child = 2 * child + 1;
}
a[root] = tmp;
}
void HeapSort(int *a, int len)
{
int i, tmp;
for(i = len / 2 -1; i >= 0; i--)
{
AdjustHeap(a, i, len - 1);
}
for (i = len - 1; i > 0; i--)
{
tmp = a[0];
a[0] = a[i];
a[i] = tmp;
AdjustHeap(a, 0, i - 1);
}
}
7 归并排序
void Merge(int *a, int start, int middle, int end)
{
if (NULL == a)
{
return;
}
int len = end - start + 1;
int i = start;
int j = middle + 1;
int *tmp = (int *)malloc(sizeof(int)*len);
int Index = 0;
while(i <= middle && j <= end)
{
tmp[Index++] = (a[i] <= a[j] ? a[i++] : a[j++]);
}
while(i <= middle)
{
tmp[Index++] = a[i++];
}
while(j <= end)
{
tmp[Index++] = a[j++];
}
Index = 0;
while (Index < len)
{
a[start++] = tmp[Index++];
}
free(tmp);
}
void MergeSort(int *a, int start, int end)
{
int middle;
if (NULL == a)
{
return;
}
if (start < end)
{
middle = (start + end) / 2;
sort(a, start, middle);
sort(a, middle + 1, end);
Merge(a, start, middle, end);
}
}