Best way to insert sorted in a list

logonveera at gmail.com logonveera at gmail.com
Fri Sep 8 14:39:10 EDT 2017


On Saturday, June 18, 2011 at 2:23:10 AM UTC+5:30, SherjilOzair wrote:
> There are basically two ways to go about this.
> One is, to append the new value, and then sort the list.
> Another is to traverse the list, and insert the new value at the
> appropriate position.
> 
> The second one's complexity is O(N), while the first one's is O(N *
> log N).
> 
> Still, the second one works much better, because C code is being used
> instead of pythons.
> 
> Still, being a programmer, using the first way (a.insert(x);
> a.sort()), does not feel right.
> 
> What has the community to say about this ? What is the best (fastest)
> way to insert sorted in a list ?

a = []
num = int(input('How many numbers: '))
for n in range(num):
    numbers = int(input('Enter values:'))
    a.append(numbers)

b = sorted(a)
print(b)
c = int(input("enter value:"))
for i in range(len(b)):
    if b[i] > c:
        index = i
        break
d = b[:i] + [c] + b[i:]
print(d)



More information about the Python-list mailing list