数组中找出最小的K个数

题目

给出一个数组,找出K个最小的值

例如给出数组{5,2,4,3,1},给定K值3,则输出结果为{2,3,1}

程序

先给出第一个版本的程序

 1     public static void printKNum(int[] source, int k) {//算法入口
 2         if (k <= 0) {
 3             System.out.println("请出入合法的K值");
 4         } else if (source.length <= k) {//如果数组的长度小于等于K,则全部输出
 5             System.out.println(Arrays.toString(source));
 6         } else {
 7             int size = 1;//记录链表的长度
 8             Node end = new Node(source[0]);
 9             for (int i = 1; i < source.length; i++) {//迭代N次
10                 if (source[i] < end.value) {//如果值小与最后一个的value,则进行插入到列表的操作
11                     findSideAndInsert(source[i], end);
12                     size++;
13                     if (size > k) {
14                         end = end.last;
15                     }
16                 }
17             }
18             end.printLastAll();
19         }
20     }
21 
22     private static void findSideAndInsert(int value, Node end) {//迭代K次,且列表有序
23         if (end.last == null) {
24             end.last = new Node(value);
25         } else {
26             if (value < end.last.value) {
27                 findSideAndInsert(value, end.last);
28             } else {
29                 Node current = new Node(value);
30                 current.last = end.last;
31                 end.last = current;
32             }
33         }
34     }
35 
36     private static class Node {
37         int value;
38         Node last;
39 
40         public Node(int value) {
41             this.value = value;
42         }
43 
44         public void printLastAll() {
45             System.out.println(this.value);
46             if (last != null) {
47                 this.last.printLastAll();
48             }
49         }
50     }

 

posted @ 2017-08-14 08:34  sachen  阅读(801)  评论(0编辑  收藏  举报