简体   繁体   中英

Given a list of numbers in random order, write an algorithm that works in O(nlog(n)) to find the kth smallest number in the list

I have write this algorithm but i am not sure that this is correct or not please help me to solve this problem, i am beginner in python programming language.

for n in maxN:
     alist = range(n)
     adict = {}
     for j in xrange(n):
         adict[j] = None
     random_index = random.randint(0, n-1)

     start1 = time.time()
     del_in_list(alist, random_index)
     end1 = time.time()

     start2 = time.time()
     del_in_dict(adict, random_index)
     end2 = time.time()

     start3 = time.time()
     empty(adict, random_index)
     end3 = time.time()

     y1.append(end1-start1-(end3-start3))
     y2.append(end2-start2-(end3-start3))    
 plt.plot(maxN,y1, "r--", maxN, y2)

plt.show()

Is this algorithm is correct if yes then how to improve this algorithm in linear?

There is actually an algorithm to find the Kth smallest/largest element in an unsorted list in a linear time.
In order to do it in an O(n*log(n)) complexity, all you have to do is sort the list, and then retrieve the nth element. something like :

x = sorted(your_list)
print x[n]

If you don't want the 1st element to be in position 0, just change n to n-1.

The solution may go like this for linear algorithm(make a bit of changes)

import random

#creating random list
l =list(range(1000))
random.shuffle(l)

a=min(l)
b=max(l)

ch = [0 for i in range(a,b)]

i=a
while i<=b:
    pos = l[i] - a
    ch[pos] = ch[pos] + 1
    i += 1
sum=0
pos = 0
k = int(input("enter the value of kth element to find"))
while sum<k:
    sum = ch[pos] + sum
    pos = pos +1

x= ch[pos-1] + a
print("%d is the K'th element of the list" % (x))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM