1:插入排序
#include <stdio.h>
void InsertionSort(int arr[], int length)
{
for (int i = 1; i < length; i++)
{
int key = arr[i], j = i;
for (j = i; j > 0; j--)
{
if (key < arr[j - 1])
{
arr[j] = arr[j - 1];
}
else
{
break;
}
}
arr[j] = key;
}
}
void Show(int arr[], int length)
{
for (int i = 0; i < length; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[10] = {4, 2, 8, 1, 9, 6, 10, 3, 7, 5};
Show(arr, 10);
InsertionSort(arr, 10);
Show(arr, 10);
return 0;
}
2:归并排序(分治策略)(需占用额外空间)
#include <stdio.h>
void SubMerge(int arr[], int l, int r)
{
if (l == r)
return;
int m = (l + r) / 2;
SubMerge(arr, l, m);
SubMerge(arr, m + 1, r);
int t[10];
int i = 0, j = 0, k = 0;
for (i = l, j = m + 1; i <= m || j <= r; k++)
{
if (i > m)
{
t[k] = arr[j];
j++;
continue;
}
if (j > r)
{
t[k] = arr[i];
i++;
continue;
}
if (arr[i] < arr[j])
{
t[k] = arr[i];
i++;
}
else
{
t[k] = arr[j];
j++;
}
}
for (int m = l; m <= r; m++)
{
arr[m] = t[m - l];
}
}
void MergeSort(int arr[], int length)
{
SubMerge(arr, 0, length - 1);
}
void Show(int arr[], int length)
{
for (int i = 0; i < length; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[10] = {4, 2, 8, 1, 9, 6, 10, 3, 7, 5};
Show(arr, 10);
MergeSort(arr, 10);
Show(arr, 10);
return 0;
}