简体   繁体   中英

What sorting algorithm would this be named?

I have been asked to implement a Quick Sort algorithm however I may have failed to do so and implemented something else (that still sorts). However while searching for its name I have not been able to find its real name.

Complexity seems to be O(n*ln(n)) is O(n) if the list is already sorted and O(n*n) at worst.

Here is the code :

def sort(L):
    S = [L[0]]
    for i in range(1,len(L)):
        addEnd = True
        for j in range(len(S)):
            if L[i] < S[j]:
                addEnd = False
                S.insert(j, L[i])
                break
        if addEnd:
            S.insert(len(S), L[i])
    return S

Thank you for helping me !

Your function fails if the length of the input is empty. But apart from that (whose fix is trivial), a quick Hypothesis test could not find a counterexample.

It is a not - in-place insertion sort .

A single-element list is already sorted, so your initial result is the first element of the input.
Then you iterate over each remaining element of the input, and search its position in the always-sorted result and insert it there.

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