简体   繁体   中英

how to apply certain list index to sort in python

I have been asked to sort a k messed array I have below code. I have to reduce the complexity from nlogn to nlogk .

arr = [3,2,1,4,5,6,8,10,9]
k = 2
def sortKmessedarr(arr, k):
    i = 1
    j = 0
    n = len(arr)
    while i < n:
        if arr[i] > arr[i-1]:
            pass
        else:
            arr[i-1:i+k].sort() # How to sort elements between two specific indexs
        i += 1
sortKmessedarr(arr, k)
print(arr)

I think if I apply this approach then it will become nlogk

But how to apply this sort() between two indexes.

I have also tried another approach like below:

arr = [3,2,1,4,5,6,8,10,9]
k = 2
def sortKmessedarr(arr, k):
    def merge(arr):
        arr.sort()
        print(arr)
    i = 1
    j = 0
    n = len(arr)
    while i < n:
        if arr[i] > arr[i-1]:
            pass
        else:
            merge(arr[i-1:i+k])#.sort()
        i += 1
sortKmessedarr(arr, k)
print(arr)

But still no luck

您可以将sorted与slice分配一起使用,以在语法上获得预期的效果,但是我不确定对性能(内存或速度)的影响:

arr[i-1:i+k] = sorted(a[i-1:i+k])

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