Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep a list sorted as you read elements

What is the efficient way to read elements into a list and keep the list sorted apart from searching the place for a new element in the existing sorted list and inserting in there?

like image 942
vkaul11 Avatar asked Sep 12 '25 05:09

vkaul11


1 Answers

Use a specialised data structure, in Python you have the bisect module at your disposal:

This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work.

like image 167
Óscar López Avatar answered Sep 14 '25 19:09

Óscar López