1 插入排序
1.1 直接插入排序
void insert_sort(int *arr, int size)
{
for (int i = 1; i < size; i++)
{
int end = i;
int temp = arr[end];
while (end > 0)
{
if (arr[end - 1] > temp)
{
arr[end] = arr[end - 1];
end--;
}
else
break;
}
arr[end] = temp;
}
}
1.2 折半插入排序
void b_insert_sort(int *arr, int size)
{
for (int i = 1; i < size; i++)
{
int left = 0;
int right = i - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[i] > arr[mid])
left = mid + 1;
else
right = mid - 1;
}
int temp = arr[i];
right = i;
while (right > left)
{
arr[right] = arr[right - 1];
right--;
}
arr[left] = temp;
}
}
2 交换排序
2.1 冒泡排序
void bubble_sort(int *arr, int length)
{
for (int i = 0; i < length - 1; i++)
for (int j = 0; j < length - 1 - i; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
2.2 快速排序
int partition(int a[], int low, int high)
{
int point = a[low];
while (low < high)
{
while (low < high && a[high] >= point)
high--;
swap(a, low, high);
while (low < high && a[low] <= point)
low++;
swap(a, low, high);
}
return low;
}
void quick_sort(int a[], int low, int high)
{
if (low < high)
{
int point = partition(a, low, high);
quick_sort(a, low, point - 1);
quick_sort(a, point + 1, high);
}
}
3 选择排序
3.1 简单选择排序
void select_sort(int *arr, int size)
{
int i = 0;
for (i = 0; i < size - 1; i++)
{
int min = i;
for (int j = i + 1; j < size; j++)
if (arr[j] < arr[min])
min = j;
swap(arr, i, min);
}
}
3.2 堆排序
typedef int HPDataType;
void Swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void AdjustDown(HPDataType* data, int size, int parent)
{
int maxchild = parent * 2 + 1;
while (maxchild < size)
{
if (maxchild + 1 < size && data[maxchild] < data[maxchild + 1])
{
maxchild++;
}
if (data[maxchild] > data[parent])
{
Swap(&data[maxchild], &data[parent]);
parent = maxchild;
maxchild = parent * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int arr, int n)
{
int i = 0;
for (i=(n-2)/2; i>=0; i--)
{
AdjustDown(arr, n, i);
}
for (i=n-1; i>0; i--)
{
Swap(&arr[0], arr[i]);
AdjustDwon(arr, i-1, 0);
}
}
4 归并排序
void merge_sort(int *arr, int size)
{
int *temp = (int *)malloc(size * sizeof(int));
if (temp == NULL)
{
perror("malloc fail!\n");
return;
}
int gap = 1;
while (gap < size)
{
for (int i = 0; i < size; i += 2 * gap)
{
int begin1 = i, end1 = i + gap - 1;
int begin2 = i + gap, end2 = i + 2 * gap - 1;
if (end1 >= size)
break;
if (begin2 >= size)
break;
if (end2 >= size)
end2 = size - 1;
int j = i;
while (begin1 <= end1 && begin2 <= end2)
{
if (arr[begin1] <= arr[begin2])
{
temp[j] = arr[begin1];
begin1++;
}
else
{
temp[j] = arr[begin2];
begin2++;
}
j++;
}
while (begin1 <= end1)
{
temp[j] = arr[begin1];
begin1++;
j++;
}
while (begin2 <= end2)
{
temp[j] = arr[begin2];
begin2++;
j++;
}
for (j = i; j <= end2; j++)
arr[j] = temp[j];
}
gap *= 2;
}
free(temp);
temp = NULL;
}
5 交换数组值的方法
void swap(int a[], int low, int high)
{
int t = a[low];
a[low] = a[high];
a[high] = t;
}