C++排序 插入排序 冒泡排序 快速排序 以及调用排序

C++排序问题

1.c++里面可以直接调用 sort函数排序(在包含 algorithm 头文件的情况下)

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

cmp用于自定义升降序,可参考c++调用排序函数

示例代码:

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
	int a[13]={27,99,0,8,13,64,86,16,7,10,88,25,90};
    sort(a,a+13); //void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
	for(int i=0;i<13;i++){
		cout<<a[i]<<" ";
	}

运行结果:

2.插入排序

函数如下:

void InsertSort(int a[],int n){
	int k=0;
	for(int i=0;i<n-1;i++){
		for(int j=0;j<=k;j++){
			if(a[k+1]>=a[j]){
				
			}
			else{
				int m=a[k+1];
				for(int l=k;l>=j;l--){
					a[l+1]=a[l];
				}
				a[j]=m;
				break;
			}
		}
		k++;
	}
}

3.冒泡排序

函数如下:

void BabbleSort(int a[],int n)
{
	for (int i=0;i<n;i++){
		for (int j=n-1;j>=i;j--){
			if(a[j]<a[j-1]){
				int temp=a[j];
				a[j]=a[j-1];
				a[j-1]=temp;
			}
		}
	}
}
在这里插入代码片

4. 快速排序

排序函数调用partion函数 分区递归
代码如下:

int Partion(int a[],int m,int n)
{
	int i=m+1,j=n; 
	while(i<j){
		if(a[i]>a[m]){
			while(a[j]>=a[m]){
				j--;
			}
			int temp = a[j];
			a[j] = a[i];
			a[i] = temp;
		}
		i++;
	}
	while(a[j]>a[m]){
		j--;
	}
	int temp= a[j];
	a[j]=a[m];
	a[m]=temp; 
	return j;
}
void QuickSort(int a[],int m,int n)
{
	if(m<n){
		int j=Partion(a,m,n);
		QuickSort(a,m,j-1);
		QuickSort(a,j+1,n);
	}
	else{
		return;
	}
}
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值