Selection Sort is a simple and intuitive sorting algorithm. Its algorithm principle is to first find the smallest (largest) element in the unsorted sequence, store it at the starting position of the sorted sequence, and then select it from the remaining unsorted elements. Continue to search for the smallest (largest) element among the elements and store it at the end of the sorted sequence, and so on until all elements are sorted.
There are a total of "number of arrays - 1" rounds of selection sorting, and each round of sorting is a cycle. The rules of the cycle are as follows:
1) First assume that the first number in the current cycle is the smallest number.
2) Then compare it with each subsequent number. If it is found that there is a smaller number than the current number, re-determine the minimum number and get the subscript.
3) When traversing to the end of the array, the smallest number of this round is obtained.
4) Exchange with the first number of the current loop.
For example:
importjava.util.Arrays;publicclassMain{publicstaticvoidmain(String[]args){int[]arr=newint[]{19,26,8,35,41,77};for(inti=0;i<arr.length- 1;i++){//Each loop will find the smallest number intminIndex=i;//Record the subscript of the smallest number intminNum=arr[i];//Record the smallest number for(intj=i+1;j< arr.length;j++){//Each loop will find the smallest number if(arr[j]<minNum){//If the current number is smaller than the minimum number, update the minimum number minNum=arr[j];/ /Update the minimum number minIndex=j;//Update the subscript of the minimum number}} arr[minIndex]=arr[i];//Put the minimum number to the front arr[i]=minNum;//Put the flag bit to the original position of the minimum number}for(inti=0;i<arr.length;i++){System.out.println(arr[i]);}}}
The running results are as follows:
81926354177