Data structures: Selection Sort

Selection Sort (Selection sort) is a straightforward sorting algorithm.
The basic idea is: first finding the minimum (or maximum) element in the series are not sorted, and then store it to the starting position number sequence; then continue looking for a minimum (or maximum) element from the remaining unsorted elements and then sorted into the end of the sequence. And so on, until all the elements are sorted.

 1 void select_sort(int a[],int n)
 2 {
 3     int i,j,min;
 4     for(i=0;i<n;i++)
 5     {
 6         min=i;
 7         for(j=i+1;j<n;j++)
 8         {
 9             if(a[j]<a[min]) min=j;
10         }
11         if(min!=i) 
12         {
13             int temp=a[i];
14             a[i]=a[min];
15             a[min]=temp;
16         }
17     }
18 }

 

Select the sort in C ++:

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 void select_sort(int a[],int n)
 5 {
 6     int i,j,min;
 7     for(i=0;i<n;i++)
 8     {
 9         min=i;
10         for(j=i+1;j<n;j++)
11         {
12             if(a[j]<a[min]) min=j;
13         }
14         if(min!=i) 
15         {
16             int temp=a[i];
17             a[i]=a[min];
18             a[min]=temp;
19         }
20     }
21 }
22 int main()
23 {
24     int a[]={200,87,12,100,34,26,58};
25     int ilen=sizeof(a)/sizeof(a[0]);
26     select_sort(a,ilen);
27     for(int i=0;i<ilen;i++) cout<<a[i]<<" ";
28     cout<<endl;
29     return 0;
30 }

Guess you like

Origin www.cnblogs.com/jianqiao123/p/12131023.html