⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sort.cpp

📁 三种排序算法
💻 CPP
字号:
#include <iostream>
using namespace std;
//冒泡排序
void BubbleSort(int a[],int n)
{
	if(n<=1)  return;
    for(int i=1;i<n;i++)     //把最大的数像冒泡一样移到后面,操作n-1次,即可得到正确排序
	{int temp=0;
		if(a[i-1]>a[i])
		{
			temp=a[i-1];
			a[i-1]=a[i];
			a[i]=temp;
		}
	}
	BubbleSort(a,n-1);
}
//选择排序
void SelectSort(int a[],int n){
	int k=0;
	if(n<=1) return;
	for(int i=0;i<n;i++)     //每次从当前数组中选出最大的数,然后放到当前数组的最后,操作n-1次
	{
		if(a[i]>a[k])
			k=i;
	}
	int temp=0;
	temp=a[k];
	a[k]=a[n-1];
	a[n-1]=a[k];
	SelectSort(a,n-1);
}
//快速排序
void QuickSort(int a[],int start,int end){
	if(start>=end)  return;
	int pivotpos=start;
	int pivot=a[start];
	for(int i=start+1;i<=end;i++)    //每次都将数组按照某一点分成两部分,再分别对两部分进行递归处理
	{
		if(a[i]<pivot){
			pivotpos++;
			if(pivotpos!=i){
				int temp=a[pivotpos];
				a[pivotpos]=a[i];
				a[i]=temp;
			}
		}
	}
	a[start]=a[pivotpos];
	a[pivotpos]=pivot;
	QuickSort(a,start,pivotpos-1);
	QuickSort(a,pivotpos+1,end);
}
int main(){
	int array1[6]={7,9,3,1,4,6};
	BubbleSort(array1,6);
	for(int i=0;i<6;i++)
		cout<<array1[i]<<" ";
	cout<<endl;
	SelectSort(array1,6);
	for(int i=0;i<6;i++)
		cout<<array1[i]<<" ";
	cout<<endl;
    QuickSort(array1,0,5);
	for(int i=0;i<6;i++)
		cout<<array1[i]<<" ";
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -