0

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

1
  • If your code works but you want people to suggest better options, your question is probably better suited for Code Review Commented Jan 19, 2017 at 19:49

1 Answer 1

1

You can use sorted with slice assignment to get the intended effect syntactically, but I am unsure of the impact on performance (memory or speed):

arr[i-1:i+k] = sorted(a[i-1:i+k])
Sign up to request clarification or add additional context in comments.

2 Comments

It did work, then why it was not working with .sort()
@RasmiRanjanNayak Because arr[i - 1: i + k] returns a new list, which is sorted in-place. You never capture the new list, so it gets garbage collected. Essentially, that line of code does nothing useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.