Re: Algorithm learning from scratch [2] Two simple sorting methods

(1) Sorting by selection method

Principle: Select the smallest (largest) element from the data elements to be sorted each time, and place it at the end of the sorted sequence until all the data elements to be sorted are sorted.

Steps: (1) Select the minimum value from the unordered sequence (2) Swap the selected minimum value with the first element of the unordered sequence


#include<iostream>
using namespace std;

void select(int *a,int n)
{
	for(int i = 0;i<n-1;i++) //Start from the i=0th of the unordered array
	{
		for(int j = i+1;j<n;j++) //Compare with the i+1th (that is, the latter), if it is larger than the latter, swap the smaller to the position of i
		{
			if(a[i]>a[j])
			{
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
	}
	for (int i = 0;i<n;i++)
	{
		cout << a[i] << " " << endl;
	}
}


intmain()
{
	int a[5] = {2,5,4,1,3};
	select(a,5);
	return 0;
}

(2) Sorting by bubble method

Principle: (1) Compare adjacent elements. If the first is larger than the second, swap (2) Do the same for each pair of adjacent elements until the last pair, at which point the last element should be the largest (3) Repeat the operation except for the last ( 4) Continue to do the same with fewer and fewer elements until there are no more numbers to compare

#include<iostream>
using namespace std;

void select(int *a,int n)
{
	for(int i = 0;i<n-1;i++) //The outer loop controls the number of comparisons. After each inner loop comparison is completed, the last number is the maximum number, so i+1 can ensure that the inner loop is avoided compare the last number
	{
		for(int j =0 ;j<ni-1;j++) //The inner loop compares from the beginning every time
		{
			if(a[j]>a[j+1])
			{
				int t = a[j];
				a[j] = a[j+1];
				a[j+1] = t;
			}
		}
	}
	for(int i =0;i<n;i++)
	cout << a[i] << " "	 << endl;
}


intmain()
{
	int a[5] = {5,4,2,1,3};
	select(a,5);
	return 0 ;
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325941108&siteId=291194637