在数组中查找元素key,返回查找到的下标,如没有找到返回-1
时间: 2024-09-20 12:13:48 浏览: 63
在数组中查找特定元素(key)并返回其索引的过程通常被称为线性搜索,因为它是从数组的第一个元素开始逐个比较,直到找到匹配项或遍历完整个数组。如果找到对应的元素,则返回该元素的索引;如果没有找到,由于数组的有序性或无序性不同,处理方式也不同:
1. **有序数组**(如升序排序的数组):二分查找效率较高。从中间元素开始,如果 key 小于中间元素,则在左半部分继续查找,反之则在右半部分。这个过程会不断缩小查找范围,直到找到 key 或确定不存在。
2. **无序数组**(未排序或随机排列):只能简单地从第一个元素逐个比对,直到找到或搜索完所有元素。这通常时间复杂度为 O(n),其中 n 为数组长度。
如果需要在 JavaScript 中实现这样的功能,可以编写如下的函数:
```javascript
function searchArray(array, key) {
for (let i = 0; i < array.length; i++) {
if (array[i] === key) {
return i;
}
}
return -1;
}
```
相关问题
在数组中查找元素key,返回查找的下标,没有找到返回-1,,并编写测试用例进行测试
在数组中查找特定元素`key`并返回其索引,如果找不到则返回-1,这是一个常见的线性搜索任务。这里提供一种简单的Python函数实现:
```python
def find_index(arr, key):
for i in range(len(arr)):
if arr[i] == key:
return i
return -1
```
接下来是一些测试用例:
```python
# 测试正常情况
test_cases = [
([1, 2, 3, 4, 5], 3, 2), # 3在索引2处
([0, 'a', True, None], 'a', 1), # 'a'在索引1处
([10, 20, 30], 25, -1) # 25不存在,返回-1
]
for input_array, key, expected_output in test_cases:
result = find_index(input_array, key)
assert result == expected_output, f"对于输入 {input_array} 和 key={key}, 预期输出{expected_output}, 实际得到{result}"
#
函数为二分法查找key值。数组中元素已递增排序,若找到key则返回对应的下标,否则返回-1。
好的,这是一个关于算法的问题,我能为您解答。以下是二分查找的实现方式:
```
int binarySearch(int arr[], int left, int right, int key) {
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
```
其中,参数 `arr` 是已经排好序的数组,`left` 和 `right` 是对应要查找的范围,`key` 是要查找的值。函数会不断取数组中间的值进行比较,缩小查找的范围,直到找到该值或者范围缩小到无法查找为止。如果找到了,则返回对应的下标,否则返回 -1。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)