算法需用编程语言很好地实现
ex < length; index++){
8. if(value == array[index])
9. return index;
10. }
11.
12. return FALSE;
13. }
上面的代码已经接近完整了,那么测试用例又该怎么编写呢?
1. static void test2()
2. {
3. int array[10] = {1, 2};
4. assert(0 == find(array, 10, 1));
5. assert(FALSE == find(array, 10, 10));
6. }
运行完所有的测试用例后,我们看看对原来的代码有没有什么可以优化的地方。其实,我们可以把数组转变成指针。
1. int find(int array[], int length, int value)
2. {
3. if(NULL == array || 0 == length)
4. return FALSE;
5.
6. int* start = array;
7. int* end = array + length;
8. while(start < end){
9. if(value == *start)
10. return ((int)start - (int)array)/(sizeof(int));
11. start ++;
12. }
13.
14. return FALSE;
15. }
如果上面的代码参数必须是通用的数据类型呢?
1. template
2. int find(type array[], int length, type value)
3. {
4. if(NULL == array || 0 == length)
5. return FALSE;
6.
7. type* start = array;
8. type* end = array + length;
9. while(start < end){
10. if(value == *start)
11. return ((int)start - (int)array)/(sizeof(type));
12. start ++;
13. }
14.
15. return FALSE;
16. }
此时,测试用例是不是也需要重新修改呢?
1. static void test1()
2. {
3. int array[10] = {0};
4. assert(FALSE == find
5. assert(FALSE == find
6. }
算法 相关文章:
- 一种并行算法计算微波电路的设计和实现(03-15)
- LDPC码译码算法及性能分析应用设计(04-16)
- 大唐移动FODCA算法削减同频干扰(03-09)
- 人工智能、大数据的十大类算法及其擅长的任务(10-04)
- CAN协议的错帧漏检率推导及改进过程简介(02-22)
- 专家支招:如何确保智能电表的安全性?(06-02)
