The algorithm idea of choosing sorting (Selectionsort): For N to sort the array, the n-1 order, each time to select the minimum number (or maximum number) to be sorted, and then the selected minimum number (or maximum number) and the first number of the current data set to be sorted; and so on until the sort is finished, The entire array to be sorted is also an ordered array.
This is called the selection sort, which means to select the smallest or largest number at a time to complete the sorting.
I'll follow through the code to demonstrate:
/** * Select sort * @author Li Zhangyong */import java.util.arrays;public class Demo1 {static int num=0;static void Selectsort (int[] arr) { for (int i=0;i<arr.length-1;i++) { int k=i;//assigns the leftmost corner of the array to K for (int j=k+1;j<arr.length;j++) { if (Arr[j]<arr[k]) {//in ascending order, if there is a smaller element than arr[k], the corner label of the element is stored K=j; } } if (i!=k) {//If there is a smaller element than arr[i], the element is swapped with Arr[i], and so on, to complete the array in ascending order int temp=arr[i]; ARR[I]=ARR[K]; Arr[k]=temp; System.out.println ("First" + (++num) + "Times:" +arrays.tostring (arr)); } } }public static void Main (string[] args) { Int[] arr={15,23,8,4,6,9,19}; System.out.println ("Before Sorting:" +arrays.tostring (arr)); Selectsort (arr); System.out.println ("After sorting:" +arrays.tostring (arr));}}
The results of the above code run:
Before sorting: [15, 23, 8, 4, 6, 9, 19] 1th time: [4, 23, 8, 15, 6, 9, 19] 2nd time: [4, 6, 8, 15, 23, 9, 19] 3rd time: [4, 6, 8, 9, 23, 15, 19] 4th Times: [4, 6, 8, 9, 15, 23, 19] 5th time: [4, 6, 8, 9, 15, 19, 23] After sorting: [4, 6, 8, 9, 15, 19, 23]
Finally, the average time complexity of selecting a sort is O (N2), which is unstable in terms of stability.
Note: For stability in sorting, please refer to the "classic sort of insert Sort" article in this blog.
Selection sort of classic sort