Skip to content

Instantly share code, notes, and snippets.

@benjholla
Last active October 10, 2018 15:54
Show Gist options
  • Save benjholla/726727be137de1187c7484df35383428 to your computer and use it in GitHub Desktop.
Save benjholla/726727be137de1187c7484df35383428 to your computer and use it in GitHub Desktop.
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