Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a sorted list? [closed]

What is a Pythonic way to search or manipulate sorted sequence?

like image 497
Basilevs Avatar asked Jul 07 '10 16:07

Basilevs


People also ask

How can we search for an element in a sorted list?

The idea is to find the pivot point, divide the array into two sub-arrays and perform a binary search. For a sorted (in increasing order) and rotated array, the pivot element is the only element for which the next element to it is smaller than it. Using binary search based on the above idea, pivot can be found.

Which search algorithm is best for sorted array?

Interpolation and Quadratic Binary Search. If we know nothing about the distribution of key values, then we have just proved that binary search is the best algorithm available for searching a sorted array.

How you will find out if number is present in sorted array?

Given a sorted array of integer numbers, write a function which returns zero-based position on which the specified value is located. Function should return negative value if requested number cannot be found in the array. If value occurs more than once, function should return position of the first occurrence.


2 Answers

bisect is part of the standard library - is that the sort of thing you're looking for?

like image 155
Daniel Roseman Avatar answered Sep 21 '22 05:09

Daniel Roseman


It's worth noting that there are a couple high-quality Python libraries for maintaining a sorted list which also implement fast searching: sortedcontainers and blist. Using these depends of course on how often you're inserting/removing elements from the list and needing to search. Each of those modules provide a SortedList class which efficiently maintains the items in sort order.

From the documentation for SortedList:

L.bisect_left(value)     Similar to the bisect module in the standard library, this returns     an appropriate index to insert value in L. If value is already present     in L, the insertion point will be before (to the left of) any existing     entries.  L.bisect(value)     Same as bisect_left.  L.bisect_right(value)     Same as bisect_left, but if value is already present in L, the     insertion point will be after (to the right of) any existing entries. 

Both implementations use binary search to find the correct index of the given value. There's a performance comparison page for choosing between the two modules.

Disclaimer: I am the author of the sortedcontainers module.

like image 43
GrantJ Avatar answered Sep 20 '22 05:09

GrantJ