数据结构排序算法之四大基础算法


选择排序

#include<iostream>

using namespace std;
typedef int elemtype;
//选择排序
void SelectSort(elemtype arr[], int n);
//int main()
//{
//	//elemtype arr[10] = { 2,4,6,1,3,5,10,9,8,7 };
//	elemtype arr[8] = { 4,2,5,7,3,1,8,6 };
//	HeapSort(arr,8);
//	for (int i = 0; i < 8; i++)
//	{
//		cout << arr[i] << " ";
//	}
//
//	return 0;
//}
//选择排序
void SelectSort(elemtype arr[], int n)
{
	for (int i = 0; i < n-1; i++)
	{
		elemtype min = arr[i];
		int flag = i;
		for (int j = i+1; j < n; j++)
		{
			if (min > arr[j])
			{
				min = arr[j];
				flag = j;
			}
		}
		min = arr[i];
		arr[i] = arr[flag];
		arr[flag] = min;
	}
}

插入排序

#include<iostream>

using namespace std;
typedef int elemtype;
//插入排序
void InsertSort(elemtype arr[], int n);
//int main()
//{
//	//elemtype arr[10] = { 2,4,6,1,3,5,10,9,8,7 };
//	elemtype arr[8] = { 4,2,5,7,3,1,8,6 };
//	HeapSort(arr,8);
//	for (int i = 0; i < 8; i++)
//	{
//		cout << arr[i] << " ";
//	}
//
//	return 0;
//}
//插入排序
void InsertSort(elemtype arr[], int n)
{
	for (int i = 1; i < n; i++)
	{
		elemtype temp = arr[i];
		int j = i - 1;
		while (temp < arr[j] && j >= 0)
		{
			arr[j + 1] = arr[j];
			j--;
		}
		arr[j + 1] = temp;
	}
}

冒泡排序

#include<iostream>

using namespace std;
typedef int elemtype;
//冒泡排序
void BubbleSort(elemtype arr[], int n);

//int main()
//{
//	//elemtype arr[10] = { 2,4,6,1,3,5,10,9,8,7 };
//	elemtype arr[8] = { 4,2,5,7,3,1,8,6 };
//	HeapSort(arr,8);
//	for (int i = 0; i < 8; i++)
//	{
//		cout << arr[i] << " ";
//	}
//
//	return 0;
//}
//冒泡排序
void BubbleSort(elemtype arr[], int n)
{
	for (int i = 0; i < n; i++)
	{
		int flag = 0;
		for (int j = 0; j < n-1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				elemtype temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
				flag = 1;
			}
		}
		if (flag == 0)
			break;
	}
}

希尔排序

#include<iostream>

using namespace std;
typedef int elemtype;
//希尔排序
void ShellSort(elemtype arr[], int n);

//int main()
//{
//	//elemtype arr[10] = { 2,4,6,1,3,5,10,9,8,7 };
//	elemtype arr[8] = { 4,2,5,7,3,1,8,6 };
//	HeapSort(arr,8);
//	for (int i = 0; i < 8; i++)
//	{
//		cout << arr[i] << " ";
//	}
//
//	return 0;
//}
//希尔排序
void ShellSort(elemtype arr[], int n)
{
	int gap = n;					//gao作为一个增量去进行排序,比较的两个元素间间隔了gap个元素
	while(gap>1)
	{
		gap /= 2;					//每次gap都折半对数组arr进行以gap为间隔的插入排序
									//也可以进行以gap为间隔进行冒泡排序
		for (int j = 0; j < n - gap; j++)
		{
			if (arr[j] > arr[j + gap])
			{
				elemtype temp = arr[j];
				arr[j] = arr[j + gap];
				arr[j + gap] = temp;
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值