Created
July 28, 2015 13:07
-
-
Save danielshaya/39af42c61b68b586111b to your computer and use it in GitHub Desktop.
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
package util; | |
import org.openjdk.jmh.annotations.Benchmark; | |
import org.openjdk.jmh.annotations.Scope; | |
import org.openjdk.jmh.annotations.State; | |
import org.openjdk.jmh.runner.Runner; | |
import org.openjdk.jmh.runner.options.Options; | |
import org.openjdk.jmh.runner.options.OptionsBuilder; | |
@State(Scope.Benchmark) | |
public class Sorter { | |
private static int arraySize = 50; | |
public static int[] theArray = new int[arraySize]; | |
private void randomise(){ | |
for (int i = 0; i < arraySize; i++) { | |
theArray[i] = (int) (Math.random() * 100); | |
} | |
} | |
@Benchmark | |
public void bubbleSort() { | |
randomise(); | |
// i starts at the end of the Array | |
// As it is decremented all indexes greater | |
// then it are sorted | |
for (int i = arraySize - 1; i > 1; i--) { | |
// The inner loop starts at the beginning of | |
// the array and compares each value next to each | |
// other. If the value is greater then they are | |
// swapped | |
for (int j = 0; j < i; j++) { | |
if (theArray[j] > theArray[j + 1]) { | |
//swap the values | |
int temp = theArray[j]; | |
theArray[j] = theArray[(j + 1)]; | |
theArray[(j + 1)] = temp; | |
} | |
} | |
} | |
} | |
@Benchmark | |
public void binarySearchForValue() { | |
randomise(); | |
int value = 50; | |
int lowIndex = 0; | |
int highIndex = arraySize - 1; | |
while (lowIndex <= highIndex) { | |
int middleIndex = (highIndex + lowIndex) / 2; | |
if (theArray[middleIndex] < value) lowIndex = middleIndex + 1; | |
else if (theArray[middleIndex] > value) highIndex = middleIndex - 1; | |
else { | |
lowIndex = highIndex + 1; | |
} | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
Options opt = new OptionsBuilder() | |
.include(Sorter.class.getSimpleName()) | |
.warmupIterations(5) | |
.measurementIterations(5) | |
.threads(4) | |
.forks(1) | |
.build(); | |
new Runner(opt).run(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment