Select the sort step:
1. Locate the subscript of the smallest element in the array that participates in the traversal comparison;
2. Swap the minimum element with the first element in the array that participates in the traversal comparison (if the first element is the smallest element, it will also be exchanged);
3. If there are elements in the array that need to participate in the traversal comparison, jump to step 1, otherwise the sort ends.
All of the sorts given in the fourth version of the algorithm are suitable for any data type that implements the comparable interface, and to use the number as a test case, do not work with the base data type, instead using an object such as Integer that implements the comparable interface.
Select the sort code as follows:
/** * * @author seabear * @Description Select sort each traversal always returns the subscript of the smallest element in the element that participates in the traversal and swaps the smallest element with the first element that participates in the traversal */public class Selectionsort {Pub Lic static void sort (comparable[] a) {int N = A.length;int Minflag = 0;for (int i = 0; i < N; i++) {minflag = i;for (int j = i + 1; J < N; J + +) {if (less (A[j],a[minflag])) {minflag = j;}} Exch (A,i,minflag);}} private static Boolean less (comparable v,comparable W) {return V.compareto (W) < 0;} private static void Exch (comparable[] A, int i,int j) {Comparable temp = a[i];a[i] = a[j];a[j] = temp;} private static void Show (comparable[] a) {for (int i = 0; i < a.length; i++) {System.out.print (A[i] + "");} System.out.println ();} private static Boolean Issort (Comparable[] a) {for (int i = 1; i < A.length, i++) {if (less (a[i],a[i-1])) {return false;} }return true;} public static void Main (string[] args) {integer[] a = new Integer[10];for (int i = 0; i <; i++) {a[i] = (int) (Math.ran Dom () * 10 + 1); System.out.print (A[i] + "");} System.out.println (); sort (a); Assert Issort (a); Show (A);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm (fourth edition) Java implementation of learning notes Select sort