对于任意一个数组,不知道是无序还是有序,查找是否有元素,那比较保险的方法就是遍历。
伪代码
对于任何一个数组:
Write "Please input the sum "
Read n Integer number[n] Write "Enter integer numbers, one per line" Set position to 0 While(position < n) Read in numbers[position] Set position to position + 1 Write "Search " Read search Set i to 0 Set flag to 0 While(i < n) If(search == number[i]) Write "The number is in the array." Set flag to 1
Break
If(fiag == 0) Write "The number is not in the array."
如果数组有序,那么就会好找不少。这里不妨假设数组number[n]是由小到大排序的,只需将搜索改成改成如下:
Set left to 0 Set right to n - 1 Set middle to (left ADD right) DIV 2 Set flag to 0 While(left < middle && middle < right) If(search < number[middle]) Set right to middle Set middle to (left ADD right) DIV 2 Else If(search > number[middle]) Set left to middle Set middle to (left ADD right) DIV 2 Else If(search == number[middle]) Set flag = 1 Break If(flag) Write "The number is not in the array." Else If(flag) Write "The number is in the array."
采用二分法,能极大提高搜素速度。
这里个人手动走代码测试了一下
结果算是比较正确了。就是手动走代码有点累。
标签:Set,元素,number,Write,middle,flag,查找,right,数组 From: https://www.cnblogs.com/Joci-zhuoxue/p/16771037.html