Experiment "data structure" Shandong University II: sorting algorithm

Experiment two sorting algorithm

First, the purpose of the experiment

Ownership in the implementation of various ideological sorting methods.

Second, the experimental content

1, input 2 to 20 non-zero positive integer, 0 represents the input end of the encounter, 0 does not participate in the sort.
2, the digital method of selection sort, bubble sort 1-, 2- insertion sort, 3- radix sort
3, sort radix sort can be achieved only positive integer less than 10. When the input is greater than 9, the direct output 0.
4, using the selected sort sorting methods, results and outputs the result of the method used, each with a number between "," separated, without spaces.
5, input and output format in strict accordance with the following requirements to achieve, and no less a single line of text.

code show as below:

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<string.h> 
using namespace std;
void swap(int &a,int & b){
	int t=a;
	a=b;
	b=t;
} 
void bubble(int a[],int n){//冒泡排序方法
	for(int i=0;i<n-1;i++){
		for(int j=0;j<n-i-1;j++){
			if(a[j]>a[j+1]) swap(a[j],a[j+1]);
		}
	}
	for(int i=0;i<n-1;i++)cout<<a[i]<<",";
	cout<<a[n-1]<<endl;
}
void insert(int a[],int n){//插入排序方法
	for(int i=1;i<n;i++){
		int t=a[i];
		for(int j=i-1;j>=0;j--){
			if(t<a[j]){
				a[j+1]=a[j];
				if(j==0) a[0]=t;
			}
			else{
				a[j+1]=t;
				break;
			}
		}
	}
	for(int i=0;i<n-1;i++)cout<<a[i]<<",";
	cout<<a[n-1]<<endl;
}
void radix(int a[],int n){//基数排序方法
	int b[]={0,0,0,0,0,0,0,0,0,0};
	int index=0;
	for(int i=0;i<n;i++){
		if(a[i]>=10)a[i]=0;
		b[a[i]%10]++;
	}
	for(int i=0;i<10;i++){
		if(b[i])
			for(int j=0;j<b[i];j++)a[index++]=i;
	}
	for(int i=0;i<index-1;i++)cout<<a[i]<<",";
	cout<<a[index-1]<<endl;	
}
int main(){
	int n;
	int a[25];
	cout<<"Input"<<endl;
	for(n=0;cin>>a[n]&&a[n]!=0;n++);
	cout<<"1-冒泡排序,2-插入排序,3-基数排序"<<endl;
	int choice;cin>>choice;
	cout<<"Output"<<endl;
	if(choice==1){
		cout<<"冒泡排序"<<endl;
		bubble(a,n);
	}
	else if(choice==2){
		cout<<"插入排序"<<endl;
		insert(a,n);
	}
	else if(choice==3){
		cout<<"基数排序"<<endl;
		radix(a,n);
	}
	cout<<"End"<<endl;	
	return 0;
}

Conclusion Analysis and experience:

温习了各个排序方法的代码,加深了对冒泡排序、插入排序和基数排序原理的理解。
Published 11 original articles · won praise 0 · Views 37

Guess you like

Origin blog.csdn.net/weixin_43959421/article/details/103973780