Sorting Algorithm (1)---Quick Insertion Sort

Because the algorithm is really weak, learn from scratch for yourself, slowly record the process,
come on, and because I am learning python and lua recently, I have implemented the basic

idea of ​​quick insertion sort in two languages : (Assumption is: from small to large, ascending order) Select one element K each time to insert into the sorted L[1...i] part, if L[x]>K, then K is inserted in front of L[x], To move the elements behind L[x] time complexity: best case: positive order (from small to large) only need to compare n times, no need to move, complexity O(n) worst case: reverse order Ordered (large to small), inserting the second element requires examining the first 1 element, inserting the third element requires examining the first 2 elements... inserting the nth element requires examining the first n-1 elements, etc. The sum of the difference sequence is n^2/2, so the complexity is O(n^2) Stability: stability means that there are two identical elements, whether the relative position of the sorting sequence changes, in the insertion sorting, if K Equal to L[x], insert directly after L[x], so that there is no need to move elements backward, so the insertion sort is a stable sort. Code example 1: python code: quick_insert_sort.py















def quick_insert_sort(l):
    for i in range(1, len(l)): #python array subscript starts from 0
        tmp = l[i]
        j = i - 1
        while(j >= 0 and tmp < l[j]): # Perform element backward shift operation
            l[j+1] = l[j]
            j -= 1
        l[j+1] = tmp #Place the element to be inserted at position j+1
    print('result:' + str(l))

if __name__ == '__main__':
    quick_insert_sort([74,62,97,88,8,75,49,16,9])



Code example 2: lua code quick_insert_sort.lua
function quick_insert_sort(t)
    len = table.getn(t)
    for i=2,len do --lua table subscript starts with 1
        tmp = t[i]
        j = i - 1
        while(j > 0 and tmp < t[j]) do --元素后移
            t[j+1] = t[j]
            j = j - 1
        end
    end
end

t = {65,71,21,13,84,49,106,56,98}
quick_insert_sort(t)
for _,v in ipairs(t) do
    print(v)
end

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326587704&siteId=291194637