Sheel 希尔排序 -mobai_dalao

本文展示了希尔排序的两种实现方式ShellSort和ShellSort2,通过插入排序的方式对数组进行逐步调整,逐步减小增量,最终达到完全排序的效果。示例代码中详细打印了排序过程中的元素移动情况。
#include<iostream>
#include<cstdlib>
using namespace std;


void ShellSort(int *a, int n)
{
	int r, temp;
	for (r = n / 2; r >= 1; r /= 2)
	{
		for (int i = r; i < n; i++)
		{
			temp = a[i];
			int j = i - r;
			cout << "i " << i << "    j= " << j << endl;
			while (j >= 0 && a[j] > temp)
			{
				a[j+r] = a[j];
				j -= r;
				cout << "j =" << j << "内循环" << endl;
			}
			a[j+r] = temp;/*
			if (a[j] > temp)
			{
				a[j + r] = a[j];
				a[j] = temp;
			}*/

		}
		for (int i = 0; i < n; i++)
			cout << a[i] << " ";
		cout << endl;
	}
}

void ShellSort2(int *a, int n)
{
	int r;
	for (r = n / 2; r >= 1; r /= 2)
	{
		for (int i = r; i < n; i++)
		{
			int j = i - r;
			int temp = a[i];
			while (j >= 0 && a[j] > temp)
			{
				a[j + r] = a[j];
				j -= r;
			}
			a[j + r] = temp;
		}
	}
}

int main()
{
	int a[10] = { 3,5,9,8,0,1,2,7,6,10 };
	int n = 10;
	for (int i = 0; i < 10; i++)
		cout << a[i] << " ";
	cout << endl;
	ShellSort2(a, n);
	for (int i = 0; i < 10; i++)
		cout << a[i] << " ";

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值