Find the smallest number of k in the array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.