You are on page 1of 3

 

Engineering / Computer Science

Use the following method to generate an arra…

Question

Use the following method to generate an array (arr1) of 5000 randomly generated elements.
public static int[] RandomArrayGenerator(int n) { int[] Array = new int[n]; Random r = new
Random(); for(int i=0;i<n;i++) { Array[i] = r.nextInt(1000); } return Array; } [Note that by using
nextInt(100) you will generate an integer between 0 and 100.] a. Use insertion sort to sort
arr1. b. Use RandomArrayGenerator again to create arr2 containing 5000 randomly
generated element. c. Use the static sort methods of Java's Arrays class to sort arr2. d. Time
each of the methods so that you can make a comparison of the efficiency. You can create
longs and store the system time to know when the method starts and ends. You can then
take the difference run time in milliseconds. long startTime = System.currentTimeMillis();
//call sort method here long endTime = System.currentTimeMillis();   

 Expert Answer

Step 1

va

util.Arrays;
util.Random;

Sorting {
ic static int[] RandomArrayGenerator(int n) {
int[] Array = new int[n];
Random r = new Random();
for (int i = 0; i < n; i++) {
Array[i] = r.nextInt(1000);
}
return Array;
ethod to sort an array of given size, using insertion sort algorithm
ic static void insertionSort(int array[]) {
// looping from i=0 to i=n-1
for (int i = 0; i < array.length; i++) {
// fetching value at index i as key (value to insert at pr
int key = array[i];
// setting i-1 as j
int j = i - 1;
// looping as long as j>=0 and array[j]>key
while (j >= 0 && array[j] > key) {
// shifting element at j one place right
array[j + 1] = array[j];
// decrementing j
j--;
}
// adding key at index j+1
array[j + 1] = key;
}

ic static void main(String[] args) {


// creating an array of 5000 random integers
int[] arr1 = RandomArrayGenerator(5000);
// recording start time
long start = System.currentTimeMillis();
// sorting using the method we defined
insertionSort(arr1);
// recording end time, and calculating time needed
long stop = System.currentTimeMillis();
long time1 = stop - start;

// creating another array of same size


int[] arr2 = RandomArrayGenerator(5000);
start = System.currentTimeMillis();
// using Arrays.sort method to sort
Arrays.sort(arr2);
stop = System.currentTimeMillis();
// recording time needed
long time2 = stop - start;

// displaying both times


System.out.println("Time needed to sort arr1 using insertionSort m
System.out.println("Time needed to sort arr2 using Arrays.sort() m

// observation: Arrays.sort() runs way more faster than the method


// this is because Arrays.sort() uses quicksort algorithm, which i
// efficient and faster than insertionSort.
Step 2

OUTPUT:

Time needed to sort arr1 using insertionSort method: 23 ms


Time needed to sort arr2 using Arrays.sort() method: 4 ms

You might also like