-1

This is an implementation of quick sort which is easier for me to understand than the others I found. Although, this implementation does not appear to be "in place" as quick sort is apparently supposed to be. I'm thinking it isn't "in place" because you're returning a new array.

Am I correct in thinking that this implementation is not "in place"?

def quick_sort(sequence):
    length = len(sequence)
    if length <= 1:
        return sequence
    else:
        pivot = sequence.pop()

    items_greater = []
    items_lower = []

    for item in sequence:
        if item > pivot:
            items_greater.append(item)
        else:
            items_lower.append(item)

    return quick_sort(items_lower) + [pivot] + quick_sort(items_greater)

This is another implementation I found which I think IS an "in place" version of quick sort. -> https://stackabuse.com/quicksort-in-python/

If somebody could confirm this. I would be very appreciative. Thanks!

jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24

2 Answers2

2

No, it is not an "in place" implementation of the quick sort algorithm.

This implementation is easier to grasp, but it is very inefficient. Bear in mind that for the array that you are trying to sort, it creates a new one of the same size, then, for the half of it, it creates another one, then for the half or it another one, and so on... You will be wasting a lot of memory for big arrays.

jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24
1

It is definitely not in place - you are generating new arrays (items_lower, etc)

Igor Rivin
  • 4,632
  • 2
  • 23
  • 35