【排序算法】插入排序(直接插入排序,希尔排序)

1.插入排序(Insertion Sort)

#include<iostream>
using namespace std;
void insertSort(int arr[], int length)
{
	for (int i = 1; i < length; i++)
	{
		int end = i - 1;
		int tmp = arr[i];
		while (end >= 0)
		{
			if (arr[end] > tmp)
			{
				arr[end + 1] = arr[end];
				--end;
			}
			else
				break;
		}
		arr[end + 1] = tmp;
	}
}
int main()
{
	int arr[] = { 49, 38, 65, 97, 76, 13, 27, 49, 10 };
	int length = sizeof(arr) / sizeof(int);
	for (auto x : arr)
	{
		cout << x << " ";
	}
	cout << endl;
	insertSort(arr, length);
	for (auto a : arr)
	{
		cout << a << " ";
	}
	return 0;
}

在这里插入图片描述
时间复杂度:平均情况O(N^2) 最好情况O(N) 最坏情况O(N^2)
空间复杂度:O(1)
稳定性:稳定

2.希尔排序(Shell Sort)

#include<iostream>
using namespace std;
void Shell_Sort(int array[], int n)  
{
	int i, j, step;
	for (step = n / 2; step > 0; step = step / 2)  
	{
		for (i = 0; i < step; i++) 
		{
			for (j = i + step; j < n; j = j + step)  
			{
				if (array[j] < array[j - step])
				{
					int temp = array[j]; 
					int k = j - step;
					while (k >= 0 && temp < array[k])
					{
						array[k + step] = array[k];  
						k = k - step;
					}
					array[k + step] = temp; 
				}
			}
		}
	}
}
int main()
{
	int arr[] = { 49, 38, 65, 97, 76, 13, 27, 49, 10 };
	int length = sizeof(arr) / sizeof(int);
	for (auto x : arr)
	{
		cout << x << " ";
	}
	cout << endl;
	Shell_Sort(arr, length);
	for (auto a : arr)
	{
		cout << a << " ";
	}
	return 0;
}

在这里插入图片描述
时间复杂度:平均情况O(N^1.3) 最好情况O(N) 最坏情况O(N^2)
空间复杂度:O(1)
稳定性:不稳定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值