十大排序

終於也要打個基礎了,準備筆試面試。

十大排序原理:https://www.cnblogs.com/onepixel/articles/7674659.html

1.冒泡排序

#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <cstdio>
#include <cmath>
#include<stdlib.h>
using namespace std;
int main(){
	int n,i,j;
	cin>>n;
	int temp;
	int a[500];
	for(i=0;i<n;i++){
		cin>>a[i];
	}
	for(i=0;i<n;i++){
		for(j=1;j<n-i;j++){
			if(a[j]<a[j-1]){
				temp=a[j];
				a[j]=a[j-1];
				a[j-1]=temp;
			}
		}
	} 
	for(i=0;i<n;i++){
		cout<<a[i]<<' ';
	}
    return 0;
}
/* 

10
6 10 9 8 3 1 2 5 7 4

*/

2.選擇排序

#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <cstdio>
#include <cmath>
#include<stdlib.h>
using namespace std;
int main(){
	int n,i,j;
	cin>>n;
	int temp,min_index;
	int a[500];
	for(i=0;i<n;i++){
		cin>>a[i];
	}
	for(i=0;i<n;i++){
		min_index=i;
		for(j=i+1;j<n;j++){
			if(a[min_index]>a[j]){
				min_index=j;
			}
		}
		temp=a[min_index];
		a[min_index]=a[i];
		a[i]=temp;
	} 
	for(i=0;i<n;i++){
		cout<<a[i]<<' ';
	}
    return 0;
}
/* 

10
6 10 9 8 3 1 2 5 7 4

*/

3.插入排序

#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <cstdio>
#include <cmath>
#include<stdlib.h>
using namespace std;
int main(){
	int n,i,j;
	cin>>n;
	int temp,min_index;
	int a[500];
	for(i=0;i<n;i++){
		cin>>a[i];
	}
	for(i=1;i<n;i++){
		min_index=i;
		for(j=i;j>0;j--){
			if(a[j]<a[j-1]){
				temp=a[j-1];
				a[j-1]=a[j];
				a[j]=temp;
			}
		}
	} 
	for(i=0;i<n;i++){
		cout<<a[i]<<' ';
	}
    return 0;
}
/* 

10
6 10 9 8 3 1 2 5 7 4

for(j=0;j<n;j++){
			cout<<a[j]<<' ';
		}

*/

4.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章