I have to get K-th smallest element in unsorted array. Not to sort the whole array I am trying only sort the subarrays that include K-th element. Then I am printing all K-th from 0 to len(array)
array = [6,5,4,3,2,1]
def quick_sort(lst, k):
if len(lst) <= 1:
return lst
else:
p = (lst[0] + lst[len(lst)-1])/2
left = [x for x in lst if x <= p]
right = [x for x in lst if x > p]
if k > len(left) -1 :
k = k - len(left)+1
return quick_sort(right,k)
else:
return quick_sort(left, k)
for i in range(len(array)):
print(*quick_sort(array,i+1))
I want to get 1,2,3,4,5,6 but my code does 2,3,5,6,6,6. What I need to change?
PS THe main idea is not sorting all arrays and not using python sort functions
array = [6, 5, 4, 3, 2, 1]
def quick_sort(lst, k):
if len(lst) <= 1:
return lst
else:
p = (lst[0] + lst[-1]) / 2
left = [x for x in lst if x <= p]
right = [x for x in lst if x > p]
if k > len(left):
k = k - len(left)
return quick_sort(right, k)
else:
return quick_sort(left, k)
for i in range(len(array)):
print(*quick_sort(array, i + 1))
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.