-3

How do I create a random number array in Java of sizes 100, 200, 300, etc. for this method?

    public static void insertionSort(int[] arr){
        for(int i = 1; i < arr.length; i++){
            int current = arr[i];
            int k;
            for(k = i - 1; k >= 0 && arr[k] > current; k--){
                arr[k + 1] = arr[k];
            }
            arr[k + 1] = current;
        }
    }
}
3
  • 2
    Write some code yourself and ask a specific question Commented Jul 12, 2016 at 5:03
  • Possible duplicate of Random number array sorting Commented Jul 12, 2016 at 5:04
  • Look up Math.random() Commented Jul 12, 2016 at 5:12

2 Answers 2

1

If I understand your question, you are wanting to create an array of random numbers to then pass into the method you posted. If that is the case, you can use the following to create an array, and then change the size in accordance with your needs.

int[] arr = new int[100];

for(int i = 0; i < arr.length; i++){
    arr[i] = (Math.random() * 100);
}

This will fill each index of your array with a random number < '100'.

Sign up to request clarification or add additional context in comments.

2 Comments

you don't need arr.length-1
Corrected. Thanks.
0

I see, you want to create an array of integers. You have to iterate the step to continually generate random numbers. This code will do.

int[] array = new int[100];

for (int i = 0; i < array.length; ++i) {
    array[i] = new Random().nextInt(100);
    // this will generate not more than 100 integers
}

// show sorted result
Arrays.sort(array);
System.out.println(Arrays.toString(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.