给定一个未排序的整数数组和一个元素x,请使用前后搜索查找x是否存在于数组中。
例子 :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : Yes
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 175;
Output : No
一个简单的解决方案是执行线性搜索。当要搜索的元素是数组中的最后一个元素时,线性搜索算法始终会导致O(n)的最坏情况复杂度。用于查找值为x的元素的前后搜索算法的工作方式如下:
- 初始化索引front和back ,分别指向数组的第一个和最后一个元素。
- 如果front大于Rear ,则返回false。
- 检查前后索引处的元素x 。
- 如果找到元素x,则返回true。
- 否则递增前向和递减后向,然后转到步骤2。
关键点:
- 当元素在数组的中间或不存在时,最坏的情况是复杂度为O(n / 2)(等于O(n))。
- 当元素是数组中的第一个或最后一个元素时,最好的情况是O(1)。
C++
// CPP program to implement front and back
// search
#include
using namespace std;
bool search(int arr[], int n, int x)
{
// Start searching from both ends
int front = 0, back = n - 1;
// Keep searching while two indexes
// do not cross.
while (front <= back)
{
if (arr[front] == x || arr[back] == x)
return true;
front++;
back--;
}
return false;
}
int main()
{
int arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170};
int x = 130;
int n = sizeof(arr)/sizeof(arr[0]);
if (search(arr, n, x))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program to implement front and back
// search
class GFG {
static boolean search(int arr[], int n, int x)
{
// Start searching from both ends
int front = 0, back = n - 1;
// Keep searching while two indexes
// do not cross.
while (front <= back)
{
if (arr[front] == x || arr[back] == x)
return true;
front++;
back--;
}
return false;
}
// driver code
public static void main (String[] args)
{
int arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170};
int x = 130;
int n = arr.length;
if (search(arr, n, x))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to implement
# front and back search
def search(arr, n, x):
# Start searching from both ends
front = 0; back = n - 1
# Keep searching while two
# indexes do not cross.
while (front <= back):
if (arr[front] == x or arr[back] == x):
return True
front += 1
back -= 1
return False
# Driver code
arr = [10, 20, 80, 30, 60,
50, 110, 100, 130, 170]
x = 130
n = len(arr)
if (search(arr, n, x)):
print("Yes")
else:
print("No")
# This code is contributed by Anant Agarwal.
C#
// C# program to implement front and back
// search
using System;
public class GFG {
static bool search(int []arr, int n, int x)
{
// Start searching from both ends
int front = 0, back = n - 1;
// Keep searching while two indexes
// do not cross.
while (front <= back)
{
if (arr[front] == x || arr[back] == x)
return true;
front++;
back--;
}
return false;
}
static public void Main ()
{
int []arr = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170};
int x = 130;
int n = arr.Length;
if (search(arr, n, x))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
PHP
Javascript
输出:
Yes