Algorithm-implement the distributed search (Binary Search) C ++ and the algorithm binary
This is a basic search algorithm, because it only takes (N) Time to read the number. Therefore, when talking about this type of problem, it is assumed that the number has been read.
When the algorithm is commonly used to reduce the problem to a part (about 1/2), we consider this algorithm at the O (logn) level.
The time complexity of the split search is O (logn)
The premise is that the sequence has been sorted.
//// Main. cpp // binarySearch // Created by Alps on 14-7-24. // Copyright (c) 2014 chen. all rights reserved. // # include <iostream> int binarySearch (const int A [], int X, int N) {int start = 0, end = 0, mid; end = N; while (start <= end) {mid = (start + end)/2; if (X> A [mid]) {start = mid + 1; continue ;} else if (X <A [mid]) {end = mid-1; continue;} else {return mid ;}} return-1 ;}int main (int argc, const char * argv []) {int A [] = {1, 4, 6, 8, 19, 34, 93}; int N = sizeof () /sizeof (int); int X = 19; int locate = binarySearch (A, X, N); if (locate =-1) {printf ("Can't find the element % d \ n", X);} else {printf ("The element % d is locate in % d \ n", X, locate);} return 0 ;}
There is no principle here .. The problem is very simple ~
Write a non-recursive algorithm in C language to achieve half-fold search (Binary Search)
Char a [10] [5]; // increments in Lexicographic Order
Int search (char * x) // returns the position of an element greater than or equal to x in an ordered table.
{
Int low = 0, high = 9, mid, t;
While (low <= high)
{
Mid = (low + high)/2;
T = strcmp (a [mid], x); // compare the midpoint position with x
If (t = 0) return mid; // returns the same position
Else
If (t> 0) high = mid-1; // if x is smaller than the mid element
Else low = mid + 1;
}
Return high + 1; // returns the first element greater than x.
}
This is the binary search of a string I used ~
Modify the data type as needed...
Implementation of Binary Search Algorithm in C Language