Selection Sort

 1 /*
 2 * 1: time complexity o(n^2)
 3 * 2: good performance for items around 10-20: better than merge sort and quick sort
 4 * 3: no extra space needed
 5 * */
 6 public class SelectSort {
 7     public static void main(String[] args) {
 8         int[] nums = {3, -3, 5, 1, 1, 2, -10};
 9         //this is the make sure no index out bound
10         for (int i = 0; i < nums.length-1; i++) {
11             /* left = 0, right =lenth - 1 = 6
12             * round 1: i = 0, nums[i] = -3, from [-3, 5, 1, 1, 2, -10], the lowest index = 6
13             * swap 3 and -10, output result = [-10, -3, 5, 1, 1, 2,3]
14             * */
15             int index = i ;
16             for (int j = i+1; j < nums.length; j++) {
17                 if (nums[j]<nums[index]){
18                     index  = j ;
19                 }
20             }
21             //when it comes to here, the index already point to the lowest num from the right(unsorted)
22             //note, dont if the i is the lowest, dont need to swap with itself
23             if (i != index){
24                 int temp = nums[i] ;
25                 nums[i] = nums[index] ;
26                 nums[index] = temp ;
27             }
28         }
29         showNumber(nums);
30     }
31 
32     public static void showNumber(int[] nums) {
33         for (int i = 0; i < nums.length; i++) {
34             System.out.println("nums[i]" + nums[i]);
35         }
36     }
37 }

 

posted @ 2018-02-14 23:04  davidnyc  阅读(167)  评论(0编辑  收藏  举报