Directory (?) [+] Introduction to selection sorting algorithm
The selection sort is very similar to the bubble sort, and is a layer -by-layer process, with the difference being that the bubble sort will frequently swap positions, and the selection order is just the location of the largest element and the top swap, just once . So the time constants are smaller and more efficient than the choice sort and bubble sort, although their worst run time is O (N2). Select Sort algorithm Java implementation
Like the Java implementation of insert sort (insertsort), implement an Array tool class first. The code is as follows:[Java] View Plain copy public class arrayutils { public static void printarray (Int[] array) { system.out.print ("{"); for (int i = 0; i < array.length; i++) { system.out.print (Array[i]); if (i < array.length - 1) { system.out.print (", "); } } system.out.println ("}"); } public static void exchangeelements (INT[]&NBSP;ARRAY,&NBSP;INT&NBSP;INDEX1,&NBSP;INT&NBSP;INDEX2) { int temp = array[index1]; array[index1] = array[index2]; array[index2 ] = temp; } }
Gradually select N-1 to 1 (Java inside the array to start with the 0 tag), respectively, as the top of the n,n-1,...,2 layer, the 2nd layer after the top, only a smaller element, the sorting end. The algorithm for each top is as follows: The position of the largest element is recorded with the Maxindex variable, initialized to the top position (the default top largest), from the front one to position 0, and then the current maximum element, and the Maxindex update to the new position, if larger than the current maximum element. The loop end already knows the position of the largest element maxindex, and if the maximum element is not the top, then swap the maximum element and top. Select the Java implementation of the sort and test code as follows:[Java] View Plain copy public class selectsort { public static void main (String[] args) { int[] array = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, 8 }; system.out.println ("Before sort:"); arrayutils.printarray (array); selectsort (array); system.out.println ("After sort:"); &Nbsp; arrayutils.printarray (array); } public static void selectsort (Int[] array) { if (array == null | | &NBSP;ARRAY.LENGTH&NBSP;<&NBSP;2) { return; } int size = array.length; for (int i = size - 1; i > 0; i--) { &NBSP;&NBSP;&NBSP;&Nbsp; int maxindex = i; for (int j = i - 1; j >= 0; j--) { if (Array[j] > array[maxindex]) { maxindex = j; } } if (maxindex != i) { Arrayutils.exchangeelements (array, i, maxindex); } } } }