Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.stream.IntStream;
- public class Chap5exe1 {
- private static boolean sequential_search(int[] iterable, int item){
- boolean found = false;
- boolean stop = false;
- int current_position = 0;
- while ((current_position < iterable.length) & (!found) & (!stop)){ //!found is found == false
- if (iterable[current_position] == item){
- found = true;
- }
- else if (iterable[current_position] > item){
- stop = true;
- }
- else {
- current_position += 1;
- }
- }
- return found;
- }
- private static boolean binary_search(int[] iterable, int item) {
- if (iterable.length == 0) {
- return false;
- }
- int mid_point = iterable.length / 2;
- if (iterable[mid_point] == item){
- return true;
- }
- else if (iterable[mid_point] > item){
- return binary_search(Arrays.copyOfRange(iterable, 0, mid_point), item);
- }
- else {
- return binary_search(Arrays.copyOfRange(iterable, mid_point+1, iterable.length), item);
- }
- }
- public static void main(String[] args) {
- for(int i = 1000; i <= 10000000; i += 1000){
- int[] list = IntStream.range(0, i).toArray();
- long startTime1 = System.nanoTime();
- sequential_search(list, i);
- long stopTime1 = System.nanoTime();
- long startTime2 = System.nanoTime();
- binary_search(list, i);
- long stopTime2 = System.nanoTime();
- String output = String.format("Sequential search:%d / Binary search:%d", stopTime1-startTime1, stopTime2-startTime2);
- System.out.println(output);
- }
- }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement