Advertisement
Japhei

Info 2019.11.15

Nov 15th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. package main;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Main {
  6.  
  7.     public static void main(String[] args) throws InterruptedException {
  8.         Scanner scanner = new Scanner(System.in);
  9.         System.out.print("Länge: ");
  10.         final int length = scanner.nextInt();
  11.         System.out.print("Suche: ");
  12.         final int search = scanner.nextInt();
  13.         scanner.close();
  14.        
  15.         int a[] = new int[length];
  16.         for (int i = 0; i < length; i++) {
  17.             a[i] = i;
  18.         }
  19.        
  20.         try {
  21.             //iterativ(a, search);
  22.             recrusiv(a, search);
  23.             System.out.println("FOUND");
  24.         } catch (NumberNotFoundException e) {
  25.             System.out.println("Die gegebene Nummer konnte nicht gefunden werden.");
  26.         }
  27.        
  28.     }
  29.    
  30.     public static void iterativ(int[] a, int search) throws NumberNotFoundException {
  31.         boolean found = false;
  32.         int start = 0;
  33.         int end = a.length - 1;
  34.         while(!found) {
  35.             int mid = ((end - start) / 2) + start;
  36.             if (a[mid] >= search) {
  37.                 end = mid;
  38.             } else {
  39.                 start = mid;
  40.             }
  41.             found = a[start] == search || a[end] == search;
  42.             if (end - start >= -1 && end - start <= 1) {
  43.                 throw new NumberNotFoundException();
  44.             }
  45.         }
  46.     }
  47.    
  48.     public static boolean recrusiv(int a[], int search) throws NumberNotFoundException {
  49.         return recrusiv(a, search, 0, a.length - 1);
  50.     }
  51.    
  52.     public static boolean recrusiv(int a[], int search, int start, int end) throws NumberNotFoundException {
  53.         if (end - start >= -1 && end - start <= 1) {
  54.             throw new NumberNotFoundException();
  55.         }
  56.         final int mid = start + ((end - start) / 2);
  57.         if (a[mid] >= search) {
  58.             end = mid;
  59.         } else {
  60.             start = mid;
  61.         }
  62.         return (a[start] == search || a[end] == search) ? true : recrusiv(a, search, start, end);
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement