Algorithm Description: One of the simplest sorting algorithms is this: first, find the smallest element in the array, and second, swap it and the first element of the group for a position. Again, find the smallest element in the remaining element and swap it with the second element of the array. So reciprocating, knowing to sort the entire array. This method is called selection ordering because it is constantly selecting the smallest of the remaining elements.
Algorithm diagram:
Java code example:
import Common. Arraysgenerator;import Common. Sortable;import Java.io.ioexception;import java.util.Arrays; Public classSelection Implements Sortable<integer>{@Override Public voidsort (integer[] array) { for(inti =0; i < Array.Length; ++i) {intMinindex =i; for(intj = i + i; J < Array.Length; ++j) {if(Array[j] <Array[minindex]) {Minindex=J; } } intTMP =Array[minindex]; Array[minindex]=Array[i]; Array[i]=tmp; } } Public Static voidMain (String arg[]) throws IOException {integer[] arr= Arraysgenerator.fromfile ("Disorder.txt",1000000); Selection Selection=NewSelection (); LongStart =System.currenttimemillis (); Selection.sort (arr); LongEnd =System.currenttimemillis (); System. out. println (arrays.tostring (arr)); System. out. println (End-start); }}
Qt/c++ code Example:
voidSelection::sort (int* Arr,intLen) { for(inti =0; i < Len; ++i) {intMinindex =i; for(intj = i +1; J < Len; ++j) {if(Arr[j] <Arr[minindex]) {Minindex=J; } } intTMP =Arr[minindex]; Arr[minindex]=Arr[i]; Arr[i]=tmp; }}intMainintargcChar*argv[]) {Qcoreapplication A (argc, argv); //method of reading an array from a file, specifying the file name with the array length, returning the array pointer int*arr = Arrays::fromfile ("Disorder.txt",1000000); Selection Selection; Qtime RT; Rt.start (); Selection.sort (arr,1000000); intEl =rt.elapsed (); Qdebug ()<<el; returna.exec ();}
In general, the choice of sorting is a simple sort algorithm that is easy to understand and implement, and it has two distinct features--run time and input independent.
Little Orange Book Reading Guide (ii)--select sort