1 / 9

Binary Search

Binary Search. By Jee You Cheng. Algorithm:. Given a SORTED array and an input value , find the MIDDLE element of the array and compare it to the input. If they are equal, the value of middle is returned and yay , the input is found!! =D

Télécharger la présentation

Binary Search

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. BinarySearch By Jee You Cheng

  2. Algorithm: • Given a SORTED array and an inputvalue, find the MIDDLE element of the array and compare it to the input. If they are equal, the value of middle is returned and yay, the input is found!! =D • If they are not equal, the array will be halved accordingly. If input is less than middle element, first half is taken and vice versa. • Within this half array, the steps above are repeated.

  3. This process of halving the array is repeated until the input is found or further division is no longer possible. • When further division is no longer possible, this indicates that the input is not located within the array. Hence, a unique value will be returned instead.

  4. Code: intbinarySearch(int list[], int size, int value) { int left = 0, right = (size-1), mid, index = -1, n=0; while ( (left <= right) && (index == -1)) { mid = (left + right) / 2;

  5. if (list[mid] == value) index = mid; else if (list[mid] > value) right = mid - 1; else left = mid + 1; n++; } printf(“Number of comparisons: %d\n”, n); return index; }

  6. Tracing…. • The 3 index variables to keep track of are left, right and mid. • Size = 10, mid = (left + right) /2 • For input = 44 : 1. left = 0, right = 9, mid = (0+9) /2 = 4

  7. For input = 90 : 1. left = 0, right = 9, mid = (0+9) /2 = 4 2. left = 5, right = 9, mid = (5+9) /2 = 7 3. left = 8, right = 9, mid = (8+9) /2 = 8

  8. For input = 20 : 1. left = 0, right = 9, mid = (0+9) /2 = 4 2. left = 0, right = 3, mid = (0+3) / 2 = 1 3. left = 2, right = 3, mid = (2+3) / 2 = 2

  9. For input = 93 : 1. left = 0, right = 9, mid = (0+9) /2 = 4 2. left = 5, right = 9, mid = (5+9) /2 = 7 3. left = 8, right = 9, mid = (8+9) /2 = 8 4. left = 9, right = 9, mid = (9+9) /2 = 9

More Related