Python implements two-dimensional ordered array search, python Array
This article describes how to use Python to find two-dimensional ordered arrays. We will share this with you for your reference. The details are as follows:
Question: In a two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, input a two-dimensional array and an integer to determine whether the array contains the integer.
This question is simple but not easy to think of. I asked two students why they didn't figure out how to solve it quickly. The first response is binary search. Perform a binary search for each row and then exclude some columns during the search process. This is the basic idea that everyone can think.
Another good idea is to first select the number in the upper-right corner of the array. If the number is equal to the number to be searched, the search ends. If the number is greater than the number to be searched, remove the column where the number is located. If the number is smaller than the number to be searched, remove the row where the number is located. In this way, one row or column can be removed from each step, and the search speed is faster.
Python implementation code:
#-*-Coding: UTF-8-*-''' question: in a two-dimensional array, each row is sorted in ascending order from left to right, each column is sorted in ascending order from top to bottom. Complete a function, input a two-dimensional array and an integer to determine whether the array contains the integer. '''Def search (array, num): # parameter validity judgment ignore I = 0 j = len (array [0])-1 max_ I = len (array) -1 while I <= max_ I and j> = 0: if array [I] [j] = num: return True elif array [I] [j]> num: j = j-1 else: I = I + 1 return Falseif _ name _ = '_ main _': a = [[1, 2, 8, 9], [2, 4, 9, 12], [4, 7, 10, 13], [6, 8, 11, 15],] print search (, 14) print search (a, 7) print search (a, 0)