排序算法_冒泡|插入|选择|快排 — C++实现

主函数体

#include<iostream>
using namespace std;
#define N 100

typedef int ElemType;
void swap(ElemType&, ElemType&);
void Bubble_Sort(ElemType*, int);
void Insertion_Sort(ElemType*, int);
void Selection_Sort(ElemType*, int);

int main() {
	ElemType a[N] = { 25, 95, 83, 12, 63, 34, 32, 48, 1, 21, 29, 45, 39, 13, 35, 52, 87, 17, 78, 12, 77, 13, 85, 38, 10, 52, 33, 74, 2, 57, 6, 7, 77, 98, 55, 94, 32, 42, 51, 14, 42, 83, 74, 94, 16, 40, 9, 24, 33, 72, 91, 55, 12, 54, 4, 81, 100, 64, 68, 77, 90, 31, 11, 6, 63, 5, 52, 29, 21, 96, 33, 86, 28, 79, 19, 95, 10, 24, 53, 90, 38, 69, 19, 6, 11, 71, 24, 22, 63, 47, 20, 99, 51, 93, 36, 85, 66, 86, 33, 65 };
	/*在此处嵌入选用的排序函数*/

	/*在此处嵌入选用的排序函数*/
	for (int i = 0; i < N; i++)
		cout << a[i] << ' ';
	return 0;
}

冒泡排序

void Bubble_Sort(ElemType a[], int n) {
	int flag = 0;							//flag用于标识是否有序
	for (int i = n-1; i >=0 ; i--)			//i用于标识最后一个待排元素的位置
	{
		for (int j = 0; j < i; j++)			//j表示从0到i做一趟冒泡排序
		{
			if (a[j] > a[j + 1]) {			//从大到小排序
				swap(a[j], a[j + 1]);
				flag = 1;
			}
		}
		if (flag == 0) break;				//一趟冒泡跑下来发现没有交换,说明已经有序了
	}
}
void swap(ElemType &x, ElemType &y) {
	ElemType t;
	t = x; x = y; y = t;
}

插入排序


void Insertion_Sort(ElemType a[], int n) {
	int i, j;
	ElemType tmp;
	for (i = 1; i < n; i++)					//i用于标识未排的第一个元素的位置
	{
		tmp = a[i];							//存放未排的第一个元素
		for (j = i; j > 0; j--)				//在已排序元素中从后往前循环找tmp插入的位置
		{
			if (a[j - 1] <= tmp) break;		//找到位置了,跳出循环
			a[j] = a[j - 1];				//把大于tmp的元素挨个往后挪
		}
		a[j] = tmp;							//插入tmp的值
	}
}

选择排序

void Selection_Sort(ElemType a[], int n) {
	int minloc;
	for (int i = 0; i < n ; i++)
	{
		minloc = i;
		for (int j = i+1; j < n; j++)		//找未排序里最小元素的位置
			if (a[minloc] > a[j]) minloc = j;
		swap(a[i], a[minloc]);				//将未排序里的最小元素换到已排序的末端
	}
}

快速排序


int Partion(ElemType a[], int low, int high) {
	int pivot = a[high];
	int left, right;
	left = low;
	right = high - 1;

	while (left<right)
	{
		while (a[left] < pivot) left++;
		while (a[right] > pivot) right--;
		if (left < right) swap(a[left], a[right]);
	}
	swap(a[left], a[high]);

	return left;
}
void Quick_Sort(ElemType a[], int low, int high) {
	int p_pivot;
	if (low < high) {
		p_pivot = Partion(a, low, high);
		Quick_Sort(a, low, p_pivot - 1);
		Quick_Sort(a, p_pivot + 1, high);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值