Half-lookup of IOS algorithm (5) and half-lookup of ios Algorithm
Binary Search, also known as semi-query, has the advantage of a small number of times, fast query speed, and good average performance. Its disadvantage is that the table to be queried is an ordered table and it is difficult to insert or delete data. Therefore, the half-fold lookup method is suitable for searching frequently ordered lists without frequent changes.
Two Methods of half-Lookup
Half-lookup method:
In an ordered table, you can compare the value of the data to be searched with the value of the element in the search range. There are three situations:
1) if the data value to be searched is exactly the same as the value of the intermediate element, the index of the intermediate element value is put back.
2) If the data value to be searched is smaller than the value of the intermediate element, the first half of the entire search range is used as the new search range. Execute 1) until an equal value is found.
3) if the value of the data to be searched is greater than the value of the intermediate element, the second half of the entire search range is used as the new search range. Execute 1) until an equal value is found.
4) if no equal value is found at the end, an error message is returned.
According to the binary tree, the middle value is the root of the binary tree. The first half is divided into the left subtree, and the second half is the right subtree. The number of searches by the half lookup method is exactly the number of layers where the value is located. In the case of equal probability, it is about log2 (n + 1)-1
Code implementation:
// Main. m
// Algorithm ---- Half-Lookup
// Copyright (c) 2014 summer2014mht@sina.com. All rights reserved.
# Import <Foundation/Foundation. h>
Int main (int argc, const char * argv [])
{
Int array [] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Int count = sizeof (array)/sizeof (array [0]);
Int target = 10;
Int start = 0, end = count-1, mid = 0;
While (start <= end ){
Mid = (start + end)/2;
If (array [mid]> target ){
End = mid-1;
} Else if (array [mid] <target ){
Start = mid + 1;
} Else {
Break;
}
}
If (start <= end ){
Printf ("[% d]: % d \ n", mid, array [mid]);
} Else {
Printf ("not found \ n ");
}
Return 0;
}
5. Program questions (9 points for a question in 1st, 10 points for a question in 2nd, 19 points in total) 1. The following programs are non-Recursive Algorithms for Binary Search. Fill in the blanks:
/* Sorry, no conditional test now */public int biSeach (int a [], int x) {int n =. length; int low = 0, high = n-1, mid; while (low <= high & mid! = X)/* judgment condition */{mid = (low + high)/2; if (a [mid] = x) return mid; else if (a [mid] <x) left = mid + 1; else right = mid-1;} return-1;/* semicolon */}
2/3 × 2/5-1/3 limit 5/2 is a simple algorithm
2/3 × 2/5-1/3 limit 5/2
= 2/3 × 2/5-1/3 × 2/5
= (3 points 2 + 3 points 1) x5 points 2
= 2 out of 1X5
= 2 out of 5