线性搜索
假设该项目以随机顺序存在于数组中,并且我们必须找到一个项目。那么搜索目标项目的唯一方法就是从第一个位置开始,并将其与目标进行比较。如果项目相同,我们将返回当前项目的位置。否则,我们将转移到下一个位置。如果我们到达数组的最后一个位置但仍然找不到目标,则返回 -1。这称为线性搜索或顺序搜索。
以下是线性搜索的代码语法:
// Linear Search in c#
using System;
using System.Collections.Generic;
class GFG
{
public static int search(int[] array, int n, int x)
{
// Going through array sequencially
for (int i = 0; i < n; i++)
if (array[i] == x)
return i;
return -1;
}
}
// This code is contributed by adityapatil12.
二分查找
然而,在二分搜索中,一旦找到排序列表的中间,就将搜索量减少一半。查看中间元素以检查它是否大于或小于要搜索的值。因此,对给定列表的任一半进行搜索
下面是二分查找的代码语法:
// Linear Search in c#
using System;
using System.Collections.Generic;
class GFG
{
public static int binary(int[] arr, int x)
{
int start = 0;
int end = arr.Length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (x == arr[mid]) {
return mid;
}
else if (x > arr[mid]) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return -1;
}
}
// This code is contributed by aditya942003patil
重要差异
线性搜索 | 二分查找 |
在线性搜索中,输入数据不需要排序。 | 在二分查找中,输入数据需要按排序顺序。 |
它也称为顺序搜索。 | 也称为半区间搜索。 |
线性搜索的时间复杂度O(n)。 | 二分查找的时间复杂度为O(log n)。 |
可以使用多维数组。 | 仅使用一维数组。 |
线性搜索执行相等比较 | 二分查找执行排序比较 |
它不太复杂。 | 它更复杂。 |
这是一个非常缓慢的过程。 | 这是一个非常快的过程。 |
让我们看一个例子来比较两者:
线性搜索从 AX 中查找给定排序列表中的元素“J”
二分查找从 AX 中查找给定排序列表中的元素“J”
线性搜索示例:
// C# program to implement above approach
using System;
using System.Collections.Generic;
class GFG
{
public static int liner(int[] arr, int x)
{
for (int i = 0; i < arr.Length; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
// Driver Code
public static void Main(string[] args){
int[] arr = { 12, 114, 0, 4, 9 };
int search = liner(arr, 4); // Here we are searching for 10 element in
// the array which is not present in the
// array so, it will print -1
Console.Write(search);
}
}
//this code is contributed by aditya942003patil
输出
在索引处找到的元素:3
时间复杂度: O(n),其中 n 是输入数组的大小。最坏的情况是数组中不存在目标元素,并且该函数必须遍历整个数组才能找出该元素。
辅助空间: O(1),函数仅使用恒定量的额外空间来存储变量。使用的额外空间量不取决于输入数组的大小。
二进制搜索示例:
using System;
using System.Collections.Generic;
class GFG
{
public static int binary(int[] arr, int x)
{
int start = 0;
int end = arr.Length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (x == arr[mid]) {
return mid;
}
else if (x > arr[mid]) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return -1;
}
// Driver Code
public static void Main(string[] args){
int[] arr = { 2, 4, 5, 7, 14, 17, 19, 22 };
int search = binary(arr, 22);
Console.Write(search);
}
}
// This code is contributed by aditya942003patil
输出
7
时间复杂度: O(log n) – 二分搜索算法在每一步将输入数组分成两半,将搜索空间减少一半,因此具有对数阶的时间复杂度。
辅助空间: O(1) – 二分查找算法只需要常数空间来存储低、高、中索引,不需要任何额外的数据结构,因此其辅助空间复杂度为 O(1)。