**
排序****
1.插入排序(直接插入排序,希尔排序)
2.选择排序(选择排序,堆排序)
3.交换排序(冒泡排序,快速排序)
4.归并排序(归并排序)
1直接插入排序
Sort.c
#include "Sort.h"
//插入排序
void InsertSort(int*a, int n)
{
assert(a);
for (int i = 0; i < n - 1; ++i)
{
//把end+1的数据插入[0.end]的有序区间
int end = i;
int tmp = a[end + 1];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + 1] = a[end];
--end;
}
else
{
break;
}
}
a[end + 1] = tmp;
}
}
```c
Sort.h
#pragma once
#include <stdio.h>
#include <assert.h>
//插入排序
void InsertSort(int*a, int n);
Test.c
#include "Sort.h"
void PrintArray(int*a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", a[i]);
}
printf("\n");
}
void TestInsertSort()
{
int a[] = {
3, 1, 4, 1, 7, 9, 8, 2, 0, 5 };
PrintArray(a, sizeof(a) / sizeof(int));
InsertSort(a, sizeof(a) / sizeof(int));
PrintArray(a, sizeof(a) / sizeof(int));
}
int main()
{
TestInsertSort();
return 0;
}
2.希尔排序
(1)预排序(先把数组派到接近有序)
(2)再直接插入排序
gap越大,前面大的数据可以越快到后面,后面小的数,可以越快到前面。但是gap越大,越不接近有序。
gap越小越接近有序。若gap==1就相当于直接插入排序,就有序了。
```c
Sort.c`
#include "Sort.h"
void PrintArray(int*a, int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", a[i]);
}
printf("\n");
}
//插入排序
void InsertSort(int*a, int n)
{
assert(a);
for (int i = 0; i < n - 1; ++i)
{
//把end+1的数据插入[0.end]的有序区间
int end = i;
int tmp = a[end + 1];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + 1] = a[end];
--end;
}
else
{
break;
}
}
a[end + 1] = tmp;
}
}
//希尔排序
void ShellSort(int* a, int n)
{
int gap = n;
while (gap > 1)
{
gap = gap / 3 + 1;//保证最后一次一定是1
for (int i = 0; i < n - gap; ++i)
{
int end = i;
int tmp = a[end + gap];
while (end >= 0)
{
if (tmp < a[end])
{
a[end + gap] = a[end];
end -= gap;
}
else
{
break;
}
}
a[end + gap] = tmp;
}
//PrintArray(a, n);
}
}
Sort.h
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <time.h>
//排序实现的接口
void PrintArray(int*a, int n);
//插入排序
void InsertSort(int*a, int n);
//希尔排序
void ShellSort(int*a, int n);
Test.c
#include "Sort.h"
void TestInsertSort()
{
int a[] = {
3, 1, 4, 1, 7, 9, 8, 2, 0, 5 };
PrintArray(a, sizeof(a) / sizeof(int));
InsertSort(a, sizeof(a) / sizeof(int));
PrintArray(a, sizeof(a) / sizeof(int));
}
void TestShellSort()
{
int a[] = {
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
PrintArray(a, sizeof(a) / sizeof(int));
ShellSort(a, sizeof(a) / sizeof(int));
//PrintArray(a, sizeof(a) / sizeof(int));
}
void TestOP()
{
srand(time(0));
const int N = 10000;
int* a1 = (int*)malloc(sizeof(int)*N);
int* a2 = (int*)malloc(sizeof(int)*N);
int* a3 = (int*)malloc(sizeof(int)*N);
int* a4 = (int*)malloc(sizeof(int)*N);
int* a5 = (int*)malloc(sizeof(int)*N);
int* a6 = (int*)malloc(sizeof(int)*N);
for (int i = 0; i < N; ++i)
{
a1[i] = rand();
a2[i] = a1[i];
a3[i] = a1[i];
a4[i] = a1[i];
a5[i] = a1[i];
a6[i] = a1[i];
}
int begin1 = clock();
InsertSort(a1, N);
int end1 = clock();
int begin2 = clock();
ShellSort(a2, N);
int end2 = clock();
printf("InsertSort:%d\n", end1 - begin1);
printf("ShellSort:%d\n", end2 - begin2);
free(a1);
free(a2);
free(a3);
free(a4);
free(a5);
free