[C/C++] Sorting algorithm

table of Contents

Select sort

Selection sort is the simplest and most commonly used sorting algorithm. Here is a simple selection sort .
Detailed explanation of selection and sorting

#include<cstdio>
#define N 5
int main(void)
{
    
    
	int a[N]={
    
    12,3,13,45,4};
	int i,j,k,temp;
	for(i=0;i<N;i++)
	{
    
    
		k=i;
		for(j=i+1;j<N;j++)
		{
    
    
			if(a[j]<a[k])
			k=j;//记录最小的下标 
		}
		temp=a[i];
		a[i]=a[k];
		a[k]=temp;
	}
	for(i=0;i<5;i++)
	{
    
    
		printf("%d ",a[i]);
	}
	return 0;
}

It can be seen from the above that the total complexity is O(n 2 ).

Insertion sort

Here is the most intuitive direct insertion sort .

Detailed explanation of insertion sort

#include<cstdio>
#define N 5
int main(void)
{
    
    
	int a[N]={
    
    12,3,13,45,4};
	int i,j,temp;
	for(i=1;i<N;i++)
	{
    
    
		temp=a[i];//temp临时存放a[i] 
		j=i;
		while(j>0&&temp<a[j-1])//只要temp小于前一个元素a[j-1] 
		{
    
    //把a[j-1]后移一位至a[j] 
			a[j]=a[j-1];
			j--;
		}
		a[j]=temp;
	}
	for(i=0;i<5;i++)
	{
    
    
		printf("%d ",a[i]);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/114596428