常见的排序算法

#include<set>
#include<iostream>
#include<queue>
#include<vector>

using namespace std;

//插入排序,从1开始,对第i个元素,依次对比左侧元素,大于该元素则右移,至正确位置插入
template<typename t>
void sort_insert(t *arry, int len)
{
	int index = 1;
	for (; index < len; index++)
	{
		t temp = arry[index];

		int j;
		for (j = index - 1; (j >= 0 && arry[j] > temp); j--)
		{
			arry[j + 1] = arry[j];//后移
		}

		arry[j+1] = temp;
	}
}

template<typename t>
void sort_bub(t *arry, int len)
{
	bool right = false;
	for (int i = 0; (i < len - 1 && !right); i++)
	{
		right = true;

		for (int j = 0; j < len - 1 - i; j++)
		{
			if (arry[j] > arry[j + 1])
			{
				t temp = arry[j];
				arry[j] = arry[j + 1];
				arry[j + 1] = temp;

				right = false;
			}
		}
	}
}

template<typename t>
void print(t *arry, int len)
{

	for (int index = 0; index < len; index++)
	{
		cout << arry[index] << " ";
	}
}


//希尔排序,先写插入排序,改编
template<typename t>
void sort_sell(t *arry, int len)
{
	int gap = len;

	do
	{
		gap = gap / 3 + 1;

		for (int k = 0; k < gap; k++)
		{
			for (int index = gap + k; index < len; index += gap)
			{
				t temp = arry[index];

				int j;
				for (j = index - gap; (j >= 0 && arry[j] > temp); j -= gap)
				{
					arry[j + gap] = arry[j];//后移
				}

				arry[j + gap] = temp;
			}
		}

	} while (gap != 1);
}

template<typename t>
void myswap(t& a, t& b)
{
	t tepm = a;
	a = b;
	b = tepm;
}

template<typename t>
int divide(t *arry, int low, int hight)
{
	t temp = arry[low];

	while (low < hight)
	{
		while (low < hight&&arry[hight]>temp)
		{
			hight--;
		}
		myswap(arry[low], arry[hight]);

		while (low < hight&&arry[low] < temp)
		{
			low++;
		}
		myswap(arry[low], arry[hight]);
	}
	return low;
}

//快速排序
template<typename t>
void sort_quick(t *arry, int low, int hight)
{
	if (low < hight)
	{
		int pos = divide(arry, low, hight);

		sort_quick(arry, low, pos - 1);
		sort_quick(arry, pos + 1, hight);
	}
}

void main()
{
	double a[10] = { 25.5, 13.2, 22.8, 31.6, 44, 334, 4, 45, 41, 555 };
	sort_quick(a, 0, 9);
	print(a,10);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值