C++实现各种插入排序(直接,折半,希尔)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现各种插入排序(直接,折半,希尔)相关的知识,希望对你有一定的参考价值。
直接插入排序(无哨兵):
代码如下:
#include <iostream>
using namespace std;
//数组下标从0开始
void InsertSort(int *a, int len)
{
int j;
for (int i = 1; i < len; i++)
{
if (a[i - 1] > a[i])//优化一下
{
int temp = a[i];
for (j = i - 1; a[j] > temp && j >= 0; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = temp;
}
}
}
int main()
{
int a[] = { 300,124,32,534,4,124,532,52,4,21 };
InsertSort(a, 10);
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
直接插入排序(要哨兵):
代码如下:
#include <iostream>
using namespace std;
//数组下标从1开始
void InsertSort(int *a, int len)
{
int j;
for (int i = 2; i <= len; i++)
{
if (a[i - 1] > a[i])//优化一下
{
a[0] = a[i];
for (j = i - 1; a[j] > a[0]; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = a[0];
}
}
}
int main()
{
int a[] = { 0,423,4,325,234,2,412,4,234,23,42,42,423,5,215,1 };
InsertSort(a, 15);
for (int i = 1; i <= 15; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
折半插入排序(有哨兵):
代码如下:
#include <iostream>
using namespace std;
void BinsertSort(int *a, int len)
{
for (int i = 2; i <= len; i++)
{
a[0] = a[i];
int low = 1, high = i - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[0] < a[mid]) high = mid - 1;
else low = mid + 1;
}
int j;
for ( j = i - 1; j >= high + 1; j--) a[j + 1] = a[j];
a[j + 1] = a[0];
}
}
int main()
{
int a[] = { 0,12,3,342,235,35,34,53,5,3,523 };
BinsertSort(a, 10);
for (int i = 1; i <= 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
希尔排序
写法一:
代码如下:
#include <iostream>
using namespace std;
void Insert_i(int *, int, int);
void ShellSort(int *a, int len)
{//数组下标从0开始
for (int d = len / 2; d > 0; d /= 2)
{
for (int i = d; i < len; i++)
{
Insert_i(a, d, i);
}
}
}
void Insert_i(int *a, int d, int i)
{
int temp = a[i];
int j;
for ( j = i - d; j >= 0 && a[j] > temp; j -= d)
{
a[j + d] = a[j];
}
a[j + d] = temp;
}
int main()
{
int a[] = { 21,3,423,5,324,324,12,41,45,23 };
ShellSort(a, 10);
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
希尔排序
写法二:
代码如下:
#include <iostream>
using namespace std;
void Insert_i(int *, int, int);
void ShellSort(int *a, int len)
{//数组下标从1开始
for (int d = len / 2; d > 0; d /= 2)
{
Insert_i(a, len,d);
}
}
void Insert_i(int *a, int len,int d)
{
for (int i = d + 1; i <= len; i++)
{
if (a[i] < a[i - d])
{
int j;
a[0] = a[i];
for (j = i - d; j > 0 && a[0] < a[j]; j -= d)
a[j + d] = a[j];
a[j + d] = a[0];
}
}
}
int main()
{
int a[] = { 0,12,3,325,25,3,53,534,62,4,1241 };
ShellSort(a, 10);
for (int i = 1; i <= 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
以上是关于C++实现各种插入排序(直接,折半,希尔)的主要内容,如果未能解决你的问题,请参考以下文章
直接插入排序 ,折半插入排序 ,简单选择排序, 希尔排序 ,冒泡排序 ,快速排序 ,堆排序 ,归并排序的图示以及代码,十分清楚