Topic
Give an array to find the smallest value of K
For example, give the array {5,2,4,3,1}, given a K value of 3, the output is {2,3,1}
Program
First version of the program is given
1 Public Static voidPrintknum (int[] Source,intK) {//Algorithmic Entry2 if(k <= 0) {3System.out.println ("Please enter a valid K value");4}Else if(Source.length <= k) {//if the length of the array is less than or equal to K, all outputs5 System.out.println (arrays.tostring (source));6}Else {7 intsize = 1;//record the length of a linked list8Node end =NewNode (source[0]);9 for(inti = 1; i < source.length; i++) {//Iterate n timesTen if(Source[i] < End.value) {//If the value is small with the last value, then the action to insert into the list One Findsideandinsert (Source[i], end); Asize++; - if(Size >k) { -End =End.last; the } - } - } - End.printlastall (); + } - } + A Private Static voidFindsideandinsert (intValue, Node end) {//iterate k times, and the list is ordered at if(End.last = =NULL) { -End.last =NewNode (value); -}Else { - if(Value <end.last.value) { - Findsideandinsert (value, end.last); -}Else { inNode current =NewNode (value); -Current.last =End.last; toEnd.last =Current ; + } - } the } * $ Private Static classNode {Panax Notoginseng intvalue; - Node last; the + PublicNode (intvalue) { A This. Value =value; the } + - Public voidPrintlastall () { $System.out.println ( This. value); $ if(Last! =NULL) { - This. Last.printlastall (); - } the } -}
Find the smallest number of k in the array