Principle
First find the smallest (large) element in the unordered sequence, place it at the beginning of the sort sequence, and then continue looking for the smallest (large) element from the remaining unsorted elements, and place it at the end of the sorted sequence. And so on until all elements are sorted. A simple and intuitive sorting algorithm.
Example
Sort array [3,6,4,2,5,1] from large to small
Sort steps:
First trip to find the minimum number 1, put to the front (with the first digital exchange)
Before Exchange:| 3 | 6 | 4 | 2 | 5 | 1 |
After Exchange:| 1 | 6 | 4 | 2 | 5 | 3 |
The second trip finds the minimum number 2 in the remaining [6,4,2,5,3] number, swapping with the first digit of the current array
Before Exchange: | 1 | 6 | 4 | 2 | 5 | 3 |
After Exchange: | 1 | 2 | 4 | 6 | 5 | 3 |
The third trip finds the minimum number 3 in the remaining [4,6,5,3] number, swapping with the first digit of the current array
Before Exchange: | 1 | 2 | 4 | 6 | 5 | 3 |
After Exchange: | 1 | 2 | 3 | 6 | 5 | 4 |
Find the minimum number 4 in the remaining [6,5,4] number, and swap with the first digit of the current array
Before Exchange: | 1 | 2 | 3 | 6 | 5 | 4 |
After Exchange: | 1 | 2 | 3 | 4 | 5 | 6 |
The smallest of the remaining [5,6] numbers is found in the first 5
Before Exchange: | 1 | 2 | 3 | 4 | 5 | 6 |
After Exchange: | 1 | 2 | 3 | 4 | 5 | 6 |
At this point, the order is complete, output final result 1 2 3 4 5 6
Animated demos
Code reference
Static voidMain (string[] args) { int[] Intarray = {3,6,4,2,5,1 }; Selection_sort (Intarray); foreach(varIteminchIntarray) {Console.WriteLine (item); } console.readline (); } Static voidSelection_sort (int[] unsorted) { intmin, temp; for(inti =0; I < unsorted. Length-1; i++) {min=i; //gets the position of the current array minimum value for(intj = i +1; J < unsorted. Length; J + +) { if(Unsorted[min] >Unsorted[j]) {min=J; } } if(min! =i) {temp=Unsorted[i]; Unsorted[i]=Unsorted[min]; Unsorted[min]=temp; } } }
Resources
Wikipedia Http://en.wikipedia.org/wiki/Selection_sort
The choice of the base algorithm sorting selection sort