直接插入排序
![](https://i-blog.csdnimg.cn/blog_migrate/8b7caab664171dc7918cdfe826653379.gif)
void InsertSort(int* a, int n)
{
for (int i = 0; i < n - 1; ++i)
{
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;
// gap > 1时是预排序,目的让他接近有序
// gap == 1是直接插入排序,目的是让他有序
while (gap > 1)
{
//gap = gap / 2;
gap = gap / 3 + 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;
}
}
}
选择排序
![](https://i-blog.csdnimg.cn/blog_migrate/9edeba0acafc2ed65ed33e6e0f43f1be.gif)
void SelectSort(int* a, int n)
{
int begin = 0, end = n - 1;
while (begin < end)
{
int mmax = begin, mmin = begin;
for (int i = begin; i <= end; i++)
{
if (a[mmax] < a[i])
{
mmax = i;
}
if (a[mmin] > a[i])
{
mmin = i;
}
}
swap(&a[begin], &a[mmin]);
if (mmax==begin)
{
mmax = mmin;
}
swap(&a[end], &a[mmax]);
begin++;
end--;
}
}
堆排序
void settodown(int* a, int number,int father)
{
int child = father * 2 + 1;
while (child < number)
{
if (child + 1 < number && a[child + 1] > a[child])
{
++child;
}
if (a[father] < a[child])
{
swap(&a[father], &a[child]);
father = child;
child = father * 2 + 1;
}
else
{
break;
}
}
}
void HeapSort(int* a, int n)
{
//建大堆
for (int i = (n - 1 - 1) / 2; i >= 0; i--)
{
settodown(a, n,i);
}
for (int i = n - 1; i > 0; i--)
{
swap(&a[0], &a[i]);
settodown(a, i, 0);
}
}
快速排序
![](https://i-blog.csdnimg.cn/blog_migrate/7821fcad60ec57808f75ede550114067.gif)
int GetMidi(int* a, int left, int right)
{
int mid = (left + right) / 2;
if (a[left]<a[mid])
{
if (a[mid]<a[right])
{
return mid;
}
else if (a[left]<a[right])
{
return right;
}
else
{
return left;
}
}
else
{
if (a[mid]>a[right])
{
return mid;
}
else if (a[right] > a[left])
{
return left;
}
else
{
return right;
}
}
}
void quicksort(int* a, int left, int right)
{
if (left >= right)
return;
int midi = GetMidi(a, left, right);
swap(&a[midi], &a[left]);
int begin = left, end = right;
int keyi = left;
while (begin < end)
{
while (begin < end && a[end] >= a[keyi])
{
--end;
}
while (begin < end && a[begin] <= a[keyi])
{
++begin;
}
swap(&a[begin], &a[end]);
}
swap(&a[keyi], &a[begin]);
keyi = begin;
quicksort(a, left, keyi - 1);
quicksort(a, keyi + 1, right);
}
冒泡排序
void BubbleSort(int* a, int n)
{
for (int i = 0; i < n; i++)
{
int tem = 1;
for (int j = 1; j < n - i; j++)
{
if (a[j - 1] > a[j])
{
swap(&a[j - 1], &a[j]);
tem = 0;
}
}
if (tem)
{
break;
}
}
}