算法学习-排序

标题:排序
1.冒泡排序

#include <iostream>
#include <cmath>
#define MAX 1000
using namespace std;
void BubbleSort(int list[],int n);
int main(){
	int a[MAX];
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	BubbleSort(a,n);
	for(int j=0;j<n;j++){
		cout<<a[j]<<" ";
	}
	return 0;
}
void BubbleSort(int list[],int n){
	for(int i=0;i<n-1;i++){
		for(int j=0;j<n-i-1;j++){
			if(list[j]<list[j+1]){
			//std::swap(list[j],list[j+1]);
			swap(list[j],list[j+1]); 
		}
		}
	}
}



2.插入排序

#include <iostream>
#define MAX 1000
using namespace std;
void InsertSort(int r[],int n);
 int main(){
 	int n;
 	cin>>n;
 	int a[MAX];
 	for(int i=0;i<n;i++) {
 		cin>>a[i];
	 }
	InsertSort(a,n);
 	for(int j=n-1;j>=0;j--){
 		cout<<a[j]<<" ";
		
	 }
 	return 0;
 }
 void InsertSort(int r[],int n){ 
 	int i,j;
 	int temp;
 	for(i=1;i<n;i++){
 		temp=r[i];
 		j=i-1;
 		while(j>=0&&temp<r[j]){
 			r[j+1]=r[j];
 			--j;
		 }
		 r[j+1]=temp;
	 }
 }



#include <iostream>
using namespace std;
void insertsort(int a[],int n);
int main(){
	int n;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	insertsort(a,n);
	for(int j=0;j<n;j++){
		cout<<a[j]<<" ";
	}
	
	return 0;
}
void insertsort(int a[],int n){
	int in,out;
	for(int out=1;out<n;out++){//假设第一个已经出去了
		int temp=a[out];//记录正要移出去的元素
		in=out;
		while(in>0&&a[in-1]>=temp){
			a[in]=a[in-1];
			in--;
		}
		a[in]=temp;
	}
}
	
 

3.选择排序

#include <iostream>
#include <cmath>
#define MAX 1000
using namespace std;
void SelectSort(int *p,int n);
int main(){
	int a[MAX];
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	SelectSort(a,n);
	for(int j=0;j<n;j++){ 
		cout<<a[j]<<" ";
	}
	return 0; 
}
void SelectSort(int *p,int n){
	for(int i=0;i<n-1;i++){//选择n-1次 
		int min=i;//标记最小值
		for(int j=i+1;j<n;j++){//从i后面开始选择最小值 
			if(p[j]<p[min]){//比较选择最小值 
				min=j;//重新确定最小值下标 
			}
		} 
		swap(p[i],p[min]);//交换最小值 
	}
}

4.快速排序

#include <iostream>
using namespace std;

void QuickSort(int a[],int low,int high){
//对从a[low]到a[high]的关键字进行排序
	int temp;
	int i=low,j=high;
	if(low < high){
		temp=a[low];
//使小于temp的放在左边,大于temp的放在右边
		while(i<j){
			while(j>i&&a[j]>=temp) --j;//从右到左扫描找到小于temp的关键字
			if(i<j){
				a[i]=a[j];//放在temp左边
				++i;//i右移一位
			}
			while(i<j&&a[i]<=temp) ++i;//从左往右扫描找到大于temp的关键字
			if(i<j){
				a[j]=a[i];//放在temp右边
				--j;//j左移一位
			}
		}
		a[i]=temp;//将temp放在最终位置
		QuickSort(a,low,i-1);//递归对左边关键字进行排序
		QuickSort(a,i+1,high);//递归对右边关键字进行排序
	}
}
int main(){
	int n;
	cin>>n;
	int k[n];
	for(int i=0;i<n;i++){
		cin>>k[i];
	}
	QuickSort(k,0,n-1);
	for(int j=0;j<n;j++){
		cout<<k[j]<<" ";
	}
	return 0;
}

******************

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


int main(){
	int n;
	cin>>n;
	int k[n];
	for(int i=0;i<n;i++){
		cin>>k[i];
	}
	sort(k,k+n);
	for(int j=n-1;j>=0;j--){
		cout<<k[j]<<" ";
	}
	return 0;
}
发布了33 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lz970704/article/details/104987821