Instantly share code, notes, and snippets.

@benjholla /Puzzle15.java Secret
Last active Oct 10, 2018

Embed
What would you like to do?
Java Puzzle 15 (explain the behavior of this program)
import java.util.Arrays;
import java.util.Random;
public class Puzzle15 {
public static void main(String[] args) {
int[] arr = new int[10000];
Random rnd = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = rnd.nextInt(1000);
}
long unsortedTime = measureSumTime(arr);
Arrays.sort(arr);
long sortedTime = measureSumTime(arr);
String comparison = ((unsortedTime == sortedTime) ?
"==" : ((unsortedTime < sortedTime) ? "<" : ">"));
System.out.println("Unsorted Time " + comparison + " Sorted Time");
}
private static long measureSumTime(int[] arr) {
long start = System.nanoTime();
int result = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < 100) {
result += arr[i];
}
}
long time = System.nanoTime() - start;
System.out.println("Sum: " + result + " in " + time + "ns");
return time;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment