SoFunction
Updated on 2025-03-10

Using the basic C++ algorithm to realize the sorting of ten numbers

Bubble sorting method
principle:
It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if they are incorrect. The work of visiting the sequence is repeated until no exchange is needed, that is, the sequence has been sorted.

The bubbling sorting algorithm works as follows:
1. Compare adjacent elements. If the first one is bigger than the second one, exchange them for the two.

2. Do the same work for each pair of adjacent elements, from the beginning of the first pair to the end of the last pair. At this point, the last element should be the largest number.

3. Repeat the above steps for all elements except the last one.

4. Continue to repeat the above steps for fewer and fewer elements each time until there are no pairs of numbers that need to be compared.

Sample code:

Copy the codeThe code is as follows:

#include<iostream> 
using namespace std;
int main(){
//Arrange in ascending order
 int a[10]={15,13,2,3,6,5,88,-3,30,40};
 int i,j,t;
 for(i=0;i<9;i++){
  for(j=0;j<(9-i);j++){
   if(a[j]>a[j+1]){
    t=a[j+1];
    a[j+1]=a[j];
    a[j]=t;
   }
}// Through each cycle, sink a maximum number
}//A kind of 10 numbers, sinking into 9 largest numbers, you can sort it
 for(i=0;i<10;i++){
  cout<<a[i]<<'\t';
 }
 cout<<endl;
 return 0;
}

Analysis: Through comparison of pairs and sorting for the first time, the largest number 88 will be placed in the last a[9]. . . . The ninth trip, a[1]=2, and then the sorting is completed

Select sorting method
principle:
The basic idea of ​​selecting sorting is: each time, the record with the smallest keyword is selected as the i-th record in the ordered sequence.

The i-th simple selection sort refers to selecting the record with the smallest keyword from n-i+1 records through the comparison of n-i keywords, and exchanging it with the i-th record. A total of i-1 comparisons are required until all records are sorted. For example: when performing i-th selection, the k-digit record with the smallest keyword is selected from the current candidate record and exchange it with the i-th record.

Sample code:

Copy the codeThe code is as follows:

#include<iostream> 
using namespace std;
int main(){
//Arrange in ascending order
 int a[10]={15,13,2,3,6,5,88,-3,30,40};
 int i,j,t,k=0;
 for(i=0;i<9;i++){
     k=i;
  for(j=i+1;j<10;j++){
      if(a[j]<a[k]){
       k=j;
      }     
  }
  t=a[k];
  a[k]=a[i];
  a[i]=t;
 }
 for(i=0;i<10;i++){
  cout<<a[i]<<'\t';
 }
 cout<<endl;
 return 0;
}