"Abstract" in the last two months have been learning Linux drivers, the middle encountered a lot of problems, slow progress. Although not Bancor born, but still think the algorithm is necessary to learn. So the array elements to find as their own algorithm begins the first blog, good follow the ordinary programmer's blog learning, the content is basically take doctrine.
We can start with a function that looks up the following array. In one sentence, first we start with the simplest function constructs.
int find (int array[], int length, int value) {int index = 0;return Index;}
as seen here, the lookup function is just a normal function, so the first thing to judge is the legitimacy of the argument:
static void Test1 () {int array[10] = {0};assert (false = = Find (NULL, ten, Ten)); assert (false = = Find (array, 0, 10));}
as can be seen here, we do not judge the legitimacy of the parameters, then the original lookup function should be how to modify?
int find (int array[], int length, int value) {if (NULL = = Array | | 0 = = length) return false;int index = 0;return Index;}
See the code above to show that we have already judged the entry parameters. So here's the code to start writing.
int find (int array[], int length, int value) {if (NULL = = Array | | 0 = = length) return false;int index = 0;for (; index < L Ength; index++) {if (value = = Array[index]) return index; return FALSE;}
The above code is nearly complete, so how do you write the test case?
static void Test2 () {int array[10] = {1, 2};assert (0 = = Find (array, 1)), assert (FALSE = = Find (array, 10, 10));}
after running through all the test cases, let's see where the original code can be optimized. In fact, we can turn arrays into pointers.
int find (int array[], int length, int value) {if (NULL = = Array | | 0 = = length) return false;int* start = array;int* end = AR Ray + length;while (Start < end) {if (value = = *start) return ((int) start-(int) array)/(sizeof (int)); start + +;} return FALSE;}
What if the above code parameter must be a generic data type?
Template<typename type>int Find (type array[], int length, type value) {if (NULL = = Array | | 0 = = length) return false;t ype* start = array;type* End = array + length;while (Start < end) {if (value = = *start) return ((int) start-(int) array)/(s Izeof (type)); start + +;} return FALSE;}
New test Cases
static void Test1 ()//For input array error when {int array[10] = {0};assert (false = = Find<int> (NULL, 10, 10));//array is empty assert (FALSE = = find<int> (array, 0, 10));//array without elements, length 0}static void test2 ()//Normal input {int array[10] = {1, 2};assert (0 = = FIND<INT&G t; (array, 10, 1));//The element asserts in the first position (FALSE = = find<int> (array, 10, 10));//Not Found}
The algorithm begins by learning the array element to find