import java.io.PrintStream; import java.util.Collections; import java.util.ArrayList; import java.util.Random; public class RandomInts { public static void main(String[] args) { PrintStream out = System.out; // N is the number of elements in the initial list final int N = Integer.parseInt(args[0]); // the list ArrayList list = new ArrayList(); // add N random integers between 1 and MAX to the list final int MAX = 100; Random rng = new Random(100); for (int i = 0; i < N; i++) { list.add(rng.nextInt(MAX) + 1); } // output the unsorted list out.println("unsorted: " + list); // sort the list Collections.sort(list); // output the sorted list out.println("sorted : " + list); // M is the number that we want to insert into the list final int M = Integer.parseInt(args[1]); // find the position in the list to insert M int position = N; for (int i = 0; position == N && i < N; i++) { Integer j = list.get(i); if (M <= j) { position = i; } } out.println(position); // insert M into the list list.add(0); for (int i = N; i > position; i--) { list.set(i, list.get(i - 1)); } list.set(position, M); out.println("final : " + list); } }