Welcome reprint, Reprint Please be sure to indicate the source: http://blog.csdn.net/alading2009/article/details/44752297
Question 5th: Enter n integers, output the smallest K. Array
For example, enter the 1,2,3,4,5,6,7,8 of these 8 digits, then the smallest 4 digits are 1,2,3,4
Here is the sort-bubble sort, fast row, select the sort, etc., choose a change should be OK.
Code:
Package test005;
/** * Created by CQ on 2015/3/30. * Question 5th: Enter n integers, output the smallest K. (array) * For example, input 1,2,3,4,5,6,7,8 these 8 digits, then the smallest 4 digits for 1,2,3,4/public class Findkmin {//To find the smallest K element public stat with a select sort
IC void Findkmin (int[] arr, int k) {k = (Arr.length > k)? k:arr.length;
for (int i=0; i<k; i++) {int iminindex = i; for (int j=i+1; j<arr.length; j + +) {if (ARR[J) < Arr[iminindex]) {Iminindex =
J
(i) Exchange the value of the small part I to the position of the array I if (iminindex!= i) {arr[i] ^= Arr[iminindex];
Arr[iminindex] ^= arr[i];
Arr[i] ^= Arr[iminindex]; }}///print array k elements public static void Printkvalue (int[] arr, int k) {k = (Arr.length > k)? k:
Arr.length;
for (int i=0; i<k i++) {System.out.print (arr[i]+ "");
}} public static void Main (string[] args) { Int[] arr = {22,2,12,4,11,6,7,8};
Findkmin.findkmin (arr,4);
Findkmin.printkvalue (arr,4); }
}
Execution results:
Connected to the target VM, address: ' 127.0.0.1:62070 ', Transport: ' Sockets '
disconnected from the target VM, address: ' 127.0.0.1:62070 ', Transport: ' Socket '
2 4 6 7
Process finished with exit code 0