[TOC]
Select Sort Program code
Package Com.uplooking.bigdata.datastructure;import Java.util.arrays;public class Selectsort {public static void main (S Tring[] args) {int[] arr = {8,-2, 3, 9, 0, 1, 7, 6}; System.out.println ("Before sorting:" + arrays.tostring (arr)); Selectsort (arr); System.out.println ("After sorting:" + arrays.tostring (arr)); /** * Select Sort: * Each time a minimum element is found in the array to be placed in front * or to be searched from the I position, find a minimum element and an I-position tuple for Exchange * src:{8,-2, 3, 9, 0, 1, 7, 6} If the array length is n * First trip: Compare n-1 * {[-2], [8], 3, 9, 0, 1, 7, 6} * Second trip: Compare N-2 * {-2, [0], [8] , 9, [3], 1, 7, 6} * Third trip: Compare N-3 * {-2, [0], [1], 9, [8], [3], 7, 6} * Four trips: Compare N-4 * {-2, 0, 1 , [3], [9], [8], 7, 6} * v-trip: Compare n-5 * {-2, 0, 1, 3, [6], [9], [8], [7]} * Sixth lie: Compare N-6 * {-2, 0, 1, 3, 6, [7], [9], [8]} * Seventh trip: Compare N-7 * {-2, 0, 1, 3, 6, 7, 8, 9} * comparison number of times (n-1) + (n-2) + ... + 2 + 1 = (n-1 + 1) * (n-1)/2 = N (n-1)/2 = N^2/2-N/2 * Time Complex O(n^2) * * @param arr * * public static void Selectsort (int[] arr) {for (int i = 0; i < arr.length -1; i++) {for (int j = i + 1; j < Arr.length; J + +) {if (Arr[i] > Arr[j]) {//Interchange Swap (arr, I, j); }}}} private static void Swap (int[] arr, int i, int j) {/*int tmp = arr[i]; Arr[i] = Arr[j]; ARR[J] = tmp;*/Arr[i] = arr[i] ^ arr[j]; ARR[J] = Arr[i] ^ arr[j]; Arr[i] = Arr[i] ^ arr[j]; }}
Test
排序前:[8, -2, 3, 9, 0, 1, 7, 6]排序后:[-2, 0, 1, 3, 6, 7, 8, 9]
Analysis of time complexity
1.时间复杂度为:O(n^2)比较的次数(n-1) + (n-2) + ... + 2 + 1=(n-1 + 1) * (n-1)/2 = n*(n-1)/2 = n^2/2 - n/22.数据排列顺序是有可能被改变的,这取决于在比较是的比较符号(>还是>=),所以其是不稳定的排序算法。
Data structure and algorithms-select sort (Java implementation)