Advertisement
Guest User

Untitled

a guest
Feb 24th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.stream.IntStream;
  3. public class Chap5exe1 {
  4. private static boolean sequential_search(int[] iterable, int item){
  5. boolean found = false;
  6. boolean stop = false;
  7. int current_position = 0;
  8. while ((current_position < iterable.length) & (!found) & (!stop)){ //!found is found == false
  9. if (iterable[current_position] == item){
  10. found = true;
  11. }
  12. else if (iterable[current_position] > item){
  13. stop = true;
  14. }
  15. else {
  16. current_position += 1;
  17. }
  18. }
  19. return found;
  20. }
  21.  
  22. private static boolean binary_search(int[] iterable, int item) {
  23. if (iterable.length == 0) {
  24. return false;
  25. }
  26. int mid_point = iterable.length / 2;
  27. if (iterable[mid_point] == item){
  28. return true;
  29. }
  30. else if (iterable[mid_point] > item){
  31. return binary_search(Arrays.copyOfRange(iterable, 0, mid_point), item);
  32. }
  33. else {
  34. return binary_search(Arrays.copyOfRange(iterable, mid_point+1, iterable.length), item);
  35. }
  36. }
  37.  
  38.  
  39. public static void main(String[] args) {
  40. for(int i = 1000; i <= 10000000; i += 1000){
  41. int[] list = IntStream.range(0, i).toArray();
  42. long startTime1 = System.nanoTime();
  43. sequential_search(list, i);
  44. long stopTime1 = System.nanoTime();
  45. long startTime2 = System.nanoTime();
  46. binary_search(list, i);
  47. long stopTime2 = System.nanoTime();
  48. String output = String.format("Sequential search:%d / Binary search:%d", stopTime1-startTime1, stopTime2-startTime2);
  49. System.out.println(output);
  50. }
  51. }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement