首页 > 其他 > 详细

SelectSort

时间:2018-02-14 23:15:00      阅读:256      评论:0      收藏:0      [点我收藏+]
 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 }

技术分享图片

 

SelectSort

原文:https://www.cnblogs.com/davidnyc/p/8449054.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!