例:
数组:
{5, 6, 7, 6, 5, 4, 3, 4, 5, 6}
键:
4
输出:
The element 4 is found at the index 6.
说明:
我们可以通过逐行移动矩阵元素并搜索该元素来解决此方法。
但是我们可以有一个优化的解决方案,因为我们知道元素之间的差是1。
我们可以按照以下步骤操作:
取第一个元素并用给定的键减去,您将获得一个值。让我们将其存储在“ diff”变量中。
我们知道数组元素的差为1,而不是一次搜索一次,而是通过diff跳转并搜索该元素。
解决方案说明:
{5, 6, 7, 6, 5, 4, 3, 4, 5, 6}
Pass 1: i=0 arr[0] is 5 == 4 No i = i + (5 - 4) i = 1
Pass 2: i = 1 arr[1] is 6 == 4 No i = i + (6 - 4) i = 3
Pass 3: i = 3 arr[3] is 6 == 4 No i = i + (6 - 4) i = 5
Pass 4: i =5 arr[5] is 4 == 4 Yes return i
解决方案在C:
#include<stdio.h> #include<stdlib.h> int search_element(int arr[], int lenght, int key) { int diff; int itr = 0; while (itr < lenght) { if (arr[itr] == key) return itr; diff = abs(arr[itr] - key); itr += diff; } return -1; //element not found } int main() { int arr[100] = {5, 6, 7, 6, 5, 4, 3, 4, 5, 6}; int lenght = 10; int key = 4; int index = 0; index = search_element(arr, lenght, key); if(index >=0 ) printf("The key is found at index %d\n", (index + 1) ); else printf("Key not found\n"); return 0; }
输出:
The key is found at index 6
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |