C++ 插入排序 (直接插入/拆半插入/希尔排序)

前置知识

插入排序,一般也被称为直接插入排序。对于少量元素的排序,它是一个有效的算法 。插入排序是一种最简单的排序方法,它的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增1的有序表。在其实现过程使用双层循环,外层循环对除了第一个元素之外的所有元素,内层循环对当前元素前面有序表进行待插入位置查找,并进行移动 。 -----百度百科

实现代码
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
int a[10];
void insertSort(int a[], int len) {//直接插入排序
	for (int i = 1; i < len; i++) {
		if (a[i] < a[i - 1]) {
			int temp = a[i];
			int j = i - 1;
			for (; j >= 0; j--) {
				if (a[j] < temp) break;
				a[j + 1] = a[j];
			}
			a[j + 1] = temp;
		}
	}
}

void binInsertSort(int a[], int len) {//拆半插入排序
	for (int i = 1; i < len; i++) {
		if (a[i] < a[i - 1]) {
			int temp = a[i];
			int  l = 0, r = i - 1;
			while (l<=r)
			{ 
				int mid = l + r >> 1;
				if (a[mid] > temp) r = mid - 1;
				else l = mid+1;
			}
			for (int j = i - 1; j >= l; j--) a[j + 1] = a[j];
			a[r+1] = temp;
		}
	}
}

void shellSort(int a[], int len) {//希尔排序
	int d = len / 2;
	while (d>0) {
		for (int i = d; i < len; i++) {
			int temp = a[i];
			int j = i - d;
			while (j >= 0 && a[j] > temp) {
				a[j + d] = a[j];
				j = j - d;
			}
			a[j + d] = temp;
		}
		d /= 2;
	}
}
int main() {
    //排序成递增序列
	for (int i = 0; i < 10; i++) cin >> a[i];
	insertSort(a,end(a)-begin(a));         //直接插入排序
	for (int i = 0; i < 10; i++) cout << a[i] << " ";
	cout << endl;
	for (int i = 0; i < 10; i++) cin >> a[i];
	binInsertSort(a, end(a) - begin(a));   //拆半插入排序
	for (int i = 0; i < 10; i++) cout << a[i] << " ";
	cout << endl;
	for (int i = 0; i < 10; i++) cin >> a[i];
	shellSort(a, end(a) - begin(a));       //希尔排序
	for (int i = 0; i < 10; i++) cout << a[i] << " ";
	cout << endl;
}
//样例: 5 1 4 2 6 9 3 8 7 0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值