📜  二维数组的搜索算法(矩阵)

📅  最后修改于: 2022-05-13 01:56:10.468000             🧑  作者: Mango

二维数组的搜索算法(矩阵)

二维数组中的线性搜索

线性搜索是一种简单的顺序搜索算法。它用于通过遍历数组中的每个元素来查找数组中是否存在特定元素。虽然在二维数组中搜索是完全相同的,但这里需要遍历所有单元格,这样,在二维数组中搜索任何元素。

下面是二维数组中线性搜索的实现

C++
// C++ code for the above approach
#include 
using namespace std;
vector linearSearch(vector> arr, int target)
{
  for (int i = 0; i < arr.size(); i++) {
    for (int j = 0; j < arr[i].size(); j++) {
      if (arr[i][j] == target) {
        return {i, j};
      }
    }
  }
  return {-1, -1};
}
 
// Driver code
int main()
{
 
  vector> arr = { { 3, 12, 9 },
                             { 5, 2, 89 },
                             { 90, 45, 22 } };
  int target = 89;
  vector ans = linearSearch(arr, target);
  cout << "Element found at index: [" << ans[0] << " " <


Java
// Linear Search in 2D arrays
import java.util.Arrays;
 
public class GFG {
    public static void main(String[] args)
    {
        int arr[][] = { { 3, 12, 9 },
                        { 5, 2, 89 },
                        { 90, 45, 22 } };
        int target = 89;
        int ans[] = linearSearch(arr, target);
        System.out.println("Element found at index: "
                           + Arrays.toString(ans));
    }
 
    static int[] linearSearch(int[][] arr, int target)
    {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] == target) {
                    return new int[] { i, j };
                }
            }
        }
        return new int[] { -1, -1 };
    }
}


Python3
# Python code for the above approach
def linearSearch (arr, target):
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            if (arr[i][j] == target):
                return [i, j]
    return [-1, -1]
 
# Driver code
arr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]
target = 89
ans = linearSearch(arr, target)
print(f"Element found at index: [{ans[0]} {ans[1]}]")
 
# This code is contributed by Saurabh Jaiswal


C#
// Linear Search in 2D arrays
using System;
 
public class GFG {
    public static void Main(string[] args)
    {
        int[, ] arr = { { 3, 12, 9 },
                        { 5, 2, 89 },
                        { 90, 45, 22 } };
        int target = 89;
        int[] ans = linearSearch(arr, target);
        Console.WriteLine("Element found at index: ["
                          + ans[0] + "," + ans[1]+"]");
    }
 
    static int[] linearSearch(int[, ] arr, int target)
    {
        for (int i = 0; i < arr.GetLength(0); i++) {
            for (int j = 0; j < arr.GetLength(1); j++) {
                if (arr[i, j] == target) {
                    return new int[] { i, j };
                }
            }
        }
        return new int[] { -1, -1 };
    }
}
 
// This code is contributed by ukasp.


Javascript


C++
// Binary Search on sorted 2D array
#include 
using namespace std;
 
vector findAns(vector> arr, int target)
{
  int r = 0;
  int c = arr[r].size() - 1;
  while (r < arr.size() && c >= 0) {
    if (arr[r] == target) {
      return { r, c };
    }
 
    // Target lies in further row
    if (arr[r] < target) {
      r++;
    }
    // Target lies in previous column
    else {
      c--;
    }
  }
  return { -1, -1 };
}
 
// Driver Code
int main()
{
   
  // Binary search in sorted matrix
  vector> arr = { { 1, 2, 3, 4 },
                             { 5, 6, 7, 8 },
                             { 9, 10, 11, 12 } };
 
  vector ans = findAns(arr, 12);
 
  cout << "Element found at index: [";
  for(int i = 0; i < ans.size(); i++){
    if(i == ans.size() - 1)
      cout << ans[i];
    else
      cout << ans[i] << ", ";
  }
  cout << "]";
 
}
 
// This code is contributed by Samim Hossain Mondal.


Java
// Binary Search on sorted 2D array
import java.util.Arrays;
 
class GFG {
 
    static int[] findAns(int[][] arr, int target)
    {
        int r = 0;
        int c = arr[r].length - 1;
        while (r < arr.length && c >= 0) {
            if (arr[r] == target) {
                return new int[] { r, c };
            }
 
            // Target lies in further row
            if (arr[r] < target) {
                r++;
            }
            // Target lies in previous column
            else {
                c--;
            }
        }
        return new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Binary search in sorted matrix
        int arr[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 } };
        int[] ans = findAns(arr, 12);
        System.out.println("Element found at index: "
                           + Arrays.toString(ans));
    }
}


Python3
# Binary Search on sorted 2D array
def findAns(arr, target):
    r = 0;
    c = len(arr[r]) - 1;
    while (r < len(arr) and c >= 0):
        if (arr[r] == target):
            return [r, c];
 
        # Target lies in further row
        if (arr[r] < target):
            r += 1;
 
        # Target lies in previous column
        else:
            c -=1;
 
    return [ -1, -1];
 
# Driver Code
if __name__ == '__main__':
    # Binary search in sorted matrix
    arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
    ans = findAns(arr, 12);
    print("Element found at index: ", ans);
 
    # This code contributed by shikhasingrajput


C#
// Binary Search on sorted 2D array
using System;
class GFG {
 
  static int[] findAns(int[, ] arr, int target)
  {
    int r = 0;
    int c = arr.GetLength(1) - 1;
    while (r < arr.GetLength(0) && c >= 0) {
      if (arr[r, c] == target) {
        return new int[] { r, c };
      }
 
      // Target lies in further row
      if (arr[r, c] < target) {
        r++;
      }
 
      // Target lies in previous column
      else {
        c--;
      }
    }
    return new int[] { -1, -1 };
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Binary search in sorted matrix
    int[, ] arr = { { 1, 2, 3, 4 },
                   { 5, 6, 7, 8 },
                   { 9, 10, 11, 12 } };
    int[] ans = findAns(arr, 12);
    Console.Write("Element found at index: [");
    int i = 0;
    for (i = 0; i < ans.Length - 1; i++)
      Console.Write(ans[i] + " ,");
    Console.Write(ans[i] + "]");
  }
}
 
// This code is contributed by ukasp.


Javascript



输出
Element found at index: [1, 2]

二维数组中线性搜索的时间复杂度O (N * M) ,其中N是行数, M是列数。

二进制搜索 二维阵列

二进制搜索是在数组中搜索的一种有效方法。二进制搜索适用于排序数组。在每次迭代中,搜索空间被分成两半,这就是为什么二分搜索比线性搜索更有效的原因。

为什么二进制搜索对于在未排序的数组中搜索没有用?

在任何算法中应用二分搜索的基本条件是搜索空间应该是有序的。要在二维数组中执行二分搜索,需要对数组进行排序。这里给出了一个未排序的二维数组,因此无法在未排序的数组中应用二分搜索。要首先应用二分搜索,二维数组需要按照本身需要(M*N)log(M*N)时间的任何顺序进行排序。所以在这里搜索任何元素的总时间复杂度是O((M * N) log(M * N)) + O(N + M)与线性搜索的时间复杂度相比非常差,只有O (N*M) 。因此,线性搜索用于在未排序的数组中进行搜索,而不是二分搜索。

下面是二维数组中二分查找的实现

C++

// Binary Search on sorted 2D array
#include 
using namespace std;
 
vector findAns(vector> arr, int target)
{
  int r = 0;
  int c = arr[r].size() - 1;
  while (r < arr.size() && c >= 0) {
    if (arr[r] == target) {
      return { r, c };
    }
 
    // Target lies in further row
    if (arr[r] < target) {
      r++;
    }
    // Target lies in previous column
    else {
      c--;
    }
  }
  return { -1, -1 };
}
 
// Driver Code
int main()
{
   
  // Binary search in sorted matrix
  vector> arr = { { 1, 2, 3, 4 },
                             { 5, 6, 7, 8 },
                             { 9, 10, 11, 12 } };
 
  vector ans = findAns(arr, 12);
 
  cout << "Element found at index: [";
  for(int i = 0; i < ans.size(); i++){
    if(i == ans.size() - 1)
      cout << ans[i];
    else
      cout << ans[i] << ", ";
  }
  cout << "]";
 
}
 
// This code is contributed by Samim Hossain Mondal.

Java

// Binary Search on sorted 2D array
import java.util.Arrays;
 
class GFG {
 
    static int[] findAns(int[][] arr, int target)
    {
        int r = 0;
        int c = arr[r].length - 1;
        while (r < arr.length && c >= 0) {
            if (arr[r] == target) {
                return new int[] { r, c };
            }
 
            // Target lies in further row
            if (arr[r] < target) {
                r++;
            }
            // Target lies in previous column
            else {
                c--;
            }
        }
        return new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Binary search in sorted matrix
        int arr[][] = { { 1, 2, 3, 4 },
                        { 5, 6, 7, 8 },
                        { 9, 10, 11, 12 } };
        int[] ans = findAns(arr, 12);
        System.out.println("Element found at index: "
                           + Arrays.toString(ans));
    }
}

Python3

# Binary Search on sorted 2D array
def findAns(arr, target):
    r = 0;
    c = len(arr[r]) - 1;
    while (r < len(arr) and c >= 0):
        if (arr[r] == target):
            return [r, c];
 
        # Target lies in further row
        if (arr[r] < target):
            r += 1;
 
        # Target lies in previous column
        else:
            c -=1;
 
    return [ -1, -1];
 
# Driver Code
if __name__ == '__main__':
    # Binary search in sorted matrix
    arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
    ans = findAns(arr, 12);
    print("Element found at index: ", ans);
 
    # This code contributed by shikhasingrajput

C#

// Binary Search on sorted 2D array
using System;
class GFG {
 
  static int[] findAns(int[, ] arr, int target)
  {
    int r = 0;
    int c = arr.GetLength(1) - 1;
    while (r < arr.GetLength(0) && c >= 0) {
      if (arr[r, c] == target) {
        return new int[] { r, c };
      }
 
      // Target lies in further row
      if (arr[r, c] < target) {
        r++;
      }
 
      // Target lies in previous column
      else {
        c--;
      }
    }
    return new int[] { -1, -1 };
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Binary search in sorted matrix
    int[, ] arr = { { 1, 2, 3, 4 },
                   { 5, 6, 7, 8 },
                   { 9, 10, 11, 12 } };
    int[] ans = findAns(arr, 12);
    Console.Write("Element found at index: [");
    int i = 0;
    for (i = 0; i < ans.Length - 1; i++)
      Console.Write(ans[i] + " ,");
    Console.Write(ans[i] + "]");
  }
}
 
// This code is contributed by ukasp.

Javascript


输出
Element found at index: [2, 3]

在已排序的二维数组中,二分查找的时间复杂度O (N + M) ,其中N是行数, M是列数。