public class InsertionSelect { public static void select(int k, int[] A) { for(int j = 0; j < A.length; j++) { int key = A[j]; int i; // Insert A[j] into the sorted sequence A[0], A[1], ... A[j-1] if(j < k) { i = j - 1; } else { i = k - 1; } while(i >= 0 && A[i] > key) { if(i == k - 1) { A[j] = A[i]; } else { A[i + 1] = A[i]; } i = i - 1; } A[i + 1] = key; } } public static void main(String args[]) { if(args.length < 2) { System.out.println("Enter a number to select and some numbers to select from"); System.exit(1); } int[] A = new int[args.length - 1]; int numSelect = 0; try { numSelect = Integer.parseInt(args[0]); for(int j = 1; j < args.length; j++) { A[j-1] = Integer.parseInt(args[j]); } } catch (NumberFormatException e) { System.out.println("Items to select must be integers"); System.exit(1); } if(numSelect <= 0) { System.out.println("Number to select must be positive "); System.exit(1); } if(numSelect >= args.length) { numSelect = args.length - 1; } select(numSelect, A); String space = ""; for(int k=0; k < numSelect; k++) { System.out.print(space + A[k]); space = " "; } System.out.print("\n"); } }