(C ++) is inserted, selected, bubble sort algorithm source code (including test)

In this study, the use cases are based on Guo Wei's "programming and algorithms"
in Coban eyes, the Best of a course is the data structure, master data structure is to have a Better Tomorrow program, it is like worth asked: "data structures + algorithms = programming "this gives the insert, select, bubbling source is real hope that we can grasp the doorway behind them, so that a strong man!
First, select Sort

#include<iostream>
#include<cstring>
using namespace std;
void SelectionSort(int a[],int size){
	for(int i=0;i<size-1;i++){
		int temp = i;
		for(int j=i+1;j<size;j++){
			if(a[j]<a[temp])
				temp = j;
		}
		int tp = a[i];
		a[i] = a[temp];
		a[temp] = tp;
	}
}
int main()
{
	int a[5]={3,5,8,2,7};
	for(int i=0;i<5;i++)
		cout << a[i] << "," ;
	SelectionSort(a,5);
	cout << endl;
	for(int i=0;i<5;i++)
		cout << a[i] << "," ;	
	return 0;
}

Summary: wherein the core code, starting with the first element, compared to the back, to find the maximum (minimum) is labeled, after traversing the exchange line, the time complexity of O (n)
Second, insertion sort

#include<cstring>
#include<iostream>
using namespace std;
void InsertionSort(int a[],int size)
{
	for(int i=1;i<size;i++){
		for(int j=0;j<i;j++){
			if(a[j]>a[i]){
				int temp = a[i];
				for(int k=i;k>j;--k)
					a[k]=a[k-1];
				a[j]=temp;
				break;
			}
		}
	}
}
int main(){
	int a[5]={3,5,8,2,7};
	for(int i=0;i<5;i++)
		cout << a[i] << "," ;
	InsertionSort(a,5);
	cout << endl;
	for(int i=0;i<5;i++)
		cout << a[i] << "," ;	
	return 0;
}

Summary: The array is divided into left and right sides, left disordered, the right order, the goal will be inserted into the digital disorderly orderly, disorderly until the number of array elements becomes zero. In addition, there is a special tips is moving element, which is inserted into the linear table data structures stored in the order of the core algorithm, hope is worth understanding!
Third, the bubble sort

#include<iostream>
using namespace std;
void BubbleSort(int a[],int size){
	for(int i=size-1;i>0;--i){
		for(int j=0;j<i;++j){
			if(a[j]>a[j+1]){
				int temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
		}
	}
}
int main()
{
	int a[5]={3,5,8,2,7};
	for(int i=0;i<5;i++)
		cout << a[i] << "," ;
	BubbleSort(a,5);
	cout << endl;
	for(int i=0;i<5;i++)
		cout << a[i] << "," ;	
	return 0;
	
}

Summary: bubble sort array is divided into left and right sides, each the size ratio on the exchange, orderly left, right disorderly, the figures from the disorder, like blowing up like a bubble, bubble sort algorithm came into being!

Published 15 original articles · won praise 2 · Views 159

Guess you like

Origin blog.csdn.net/m0_37149062/article/details/104800023