-
-
Save benjholla/726727be137de1187c7484df35383428 to your computer and use it in GitHub Desktop.
Java Puzzle 15 (explain the behavior of this program)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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