Sorting Algorithms - Selection Sort (Recursive and Non-Recursive)

The study records in a hurry, did not have time to write carefully.
Selection sort is a simple and intuitive sorting algorithm. Its working principle is: select the smallest (or largest) element from the data elements to be sorted for the first time, store it in the starting position of the sequence, and then find the smallest (largest) element from the remaining unsorted elements element and put it at the end of the sorted sequence. And so on, until the number of all data elements to be sorted is zero. Selection sort is an unstable sorting method.

non-recursive:

void selectsort1(int *a,int n)
{
    
    
	int i,j,min_pos;
	for(i=0;i<n-1;i++)
	{
    
    	min_pos=i;
		for(j=i;j<n;j++)
		{
    
    
			if(a[min_pos]>a[j])
			{
    
    min_pos=j;}//找最小值的位置
		}
		if(i!=min_pos)
		{
    
    swap(&a[i],&a[min_pos]);}
	}
}

recursion:

void selectsort2(int *a,int n)//递归
{
    
    
	int i;
	int min_pos=0;
	if(n<2)return;
	for(i=1;i<n;i++)
	{
    
    	
		if(a[min_pos]>a[i]){
    
    min_pos=i;}
	}
	if(min_pos!=0)swap(&a[0],&a[min_pos]);
	selectsort2(a+1,--n);//这里一定要写成a+1不要写成a++了
}

I'm a little curious here, recursively passing in a++ here only arranges the first element, but writing a+1 will arrange all of them, maybe I haven't got a thorough understanding of pointers here. Hope someone can tell me why.

#include<stdio.h>

void swap(int *a,int *b)
{
    
    
	int temp;
	temp=*a;
	*a=*b;
	*b=temp;
}
void selectsort1(int *a,int n)
{
    
    
	int i,j,min_pos;
	for(i=0;i<n-1;i++)
	{
    
    	min_pos=i;
		for(j=i;j<n;j++)
		{
    
    
			if(a[min_pos]>a[j])
			{
    
    min_pos=j;}//找最小值的位置
		}
		if(i!=min_pos)
		{
    
    swap(&a[i],&a[min_pos]);}
	}
}
void selectsort2(int *a,int n)//递归
{
    
    
	int i;
	int min_pos=0;
	if(n<2)return;
	for(i=1;i<n;i++)
	{
    
    	
		if(a[min_pos]>a[i]){
    
    min_pos=i;}
	}
	if(min_pos!=0)swap(&a[0],&a[min_pos]);
	selectsort2(a+1,--n);//这里一定要写成a+1不要写成a++了
}
/*
优化
selectsort3(int *a,int n)
每次比较,选择最小值放左边,最大值放右边
缩小了循环次数
*/
int main()
{
    
    
	int a[]={
    
    3,5,1,-7,4,9,-6,8,10,4};
	int n=(int)sizeof(a)/sizeof(int);
	int i;
	//selectsort1(a,n);//非递归
	selectsort2(a,n);//递归
	for(i=0;i<n;i++)printf("%3d",a[i]);
	printf("\n");
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44627822/article/details/121455755