Guest User

Untitled

a guest
Jan 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. public static void main(String[] args) {
  2. int data[] = {9, 15, 32, 71, 78, 92, 101, 115, 117, 129, 270, 350, 470, 500};
  3. int pos = binarySearch(data, 128);
  4. System.out.println("position 128 at : " + pos);
  5. pos = binarySearch(data, 117);
  6. System.out.print("found 117 at : " + pos);
  7. }
  8.  
  9. private static int binarySearch(int[] data, int key) {
  10. int position = -1;
  11. int left = 0;
  12. int right = data.length - 1;
  13. int mid = 0;
  14.  
  15. while (left <= right) {
  16. mid = (left + right) / 2;
  17.  
  18. if (key > data[mid]) {
  19. left = mid + 1;
  20.  
  21. } else if (key < data[mid]) {
  22. right = mid - 1;
  23.  
  24. } else {
  25. position = mid;
  26. break;
  27. }
  28. }
  29. return position; //return index ของ array ที่หาเจอ ถ้าไม่เจอ return -1
  30. }
  31.  
  32. private static int binarySearch(Comparable[] data, Comparable key) {
  33. int position = 0;
  34.  
  35. return position; //return index ของ array ที่หาเจอ ถ้าไม่เจอ return -1
  36. }
Add Comment
Please, Sign In to add comment