In: Computer Science
Perform an experimental analysis to test and compares the relative running times of this method
[HINT: use the following inputs size to check each example (1000). You can generate each array using random number generator to fill the array with the pervious input size].
/** Returns the sum of the integers in given array. */
public static int example1(int[] arr) {
int n = arr.length, total = 0;
for (int j=0; j < n; j++) // loop from 0 to n-1
total += arr[j];
return total;
}
public class ArraySumTime { public static int example1(int[] arr) { int n = arr.length, total = 0; for (int j = 0; j < n; j++) // loop from 0 to n-1 total += arr[j]; return total; } public static long findTime(int size) { int arr[] = new int[size]; for(int i=0; i<size; i++) { arr[i] = (int) (Math.random() * size); } long start = System.nanoTime(); example1(arr); long end = System.nanoTime(); return (end - start); } public static void main(String[] args) { for(int size=1000; size<=1000000; size *= 2) { System.out.println("For Size: " + size + ", Time: " + findTime(size) + "ns."); } } }
************************************************** The method runs a loop for N elements, Hence its time is proportional to the size of the array given.. hence If for a size of N element, code takes T seconds.. Then for size 2N, it should ideally take 2*N time. I have coded to show how the time increases when we increase the size by a factor of 2.. However The data will keep changing in each run, because of system resources.. Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.