How does Python insertion sort work?

前端 未结 21 1511
南方客
南方客 2020-12-10 02:54

Here\'s a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don\'t know what to do, h

相关标签:
21条回答
  • 2020-12-10 03:27
    def insertionSort(alist):
        for index in range(1, len(alist)):
    
            currentvalue = alist[index]
            position = index
    
            while position > 0 and alist[position-1] > currentvalue:
                alist[position] = alist[position-1]
                print(alist)
                position -= 1
    
            alist[position] = currentvalue
    
    alist = [int(i) for i in input().split()]       
    insertionSort(alist)
    
    0 讨论(0)
  • 2020-12-10 03:28

    Insertion Sort via Recursion:

    k=1# def insertionsort(a): # should be written before k=1
    c=a[:]
    def swap(k,c,a):
        if c[k-1] > c[k]:
            c[k-1] = a[k]
            c[k] = a[k-1]
            a = c[:]
            if max(c[:k])!= c[k-1]:
                swap(k-1,c,a)
        if k < len(a)-1:
           return swap(k + 1, c,a)
        return c
    return swap(k,c,a)
    
    print(insertionsort(b))
    
    0 讨论(0)
  • 2020-12-10 03:29

    Try this one, works for both increasing and decreasing order:

    import operator
    
    def insertion_sort(arr, reverse=False):
        # check if array is empty or not
        if arr is None:
            raise TypeError("Data cannot be none")
    
        n = len(arr)
        # if length of array is less than two it is already sorted
        if n < 2:
            return arr
    
        lgt = operator.gt if reverse else operator.lt
    
        # Traverse through 1 to len(arr)
        for i in range(1, n):
            key = arr[i]
            j = i-1
            while j >= 0 and lgt(key, arr[j]):
                arr[j+1] = arr[j]
                j -= 1
            arr[j+1] = key
        return arr
    
    li = [1, 4, 8, 9, 42, 0, 36]
    print(insertion_sort(li))
    
    0 讨论(0)
  • 2020-12-10 03:32

    If we consider an array from left to right [LeftMost, ..., RightMost], an insertion sort performs the following procedure for each item:

    1. Get the current value i.
    2. Get the value j (where j = i-1 in the first iteration, or basically the first element to the left of i). In the first iteration of the while array[i] and array[j] are to consecutive elements. For example, if array = [... 60, 100, 50, ...], and array[i] is 50, then array[j] is 100.
    3. If the previous value is greater than the current one, then it swaps the two values. Basically if you had something like [..., 60, 100, 50, ...] before this operation takes place, you will end up with [..., 60, 50, 100, ...]. The idea is that you move each item i left as long as there are elements to the left of it that are lower.

      This is the key of the sort algorithm. Once you are done processing at item i, you have a sorted array from where it originally was all the way to the beggining (left most).

    4. Decrease the value of j by one. and go back to step 1 (In this example, this will lead you to compare 50 and 60 and swap them).
    If you take a look at the code carefully, you never get a the point where i >= len(s) (range is a function that creates a list, and the value i is not changed inside the loop). You can think of the variable i as an imaginary arrow, pointing to a position in the array that has all sorted elements to its left. The variable j simply moves to the left with i fixed, to swap the original array[i] value until it finds another value that is equal or lower than it.

    Sidenote (not important to understand the algorithm, but could be useful): With that in mind, you can deduce that this algorithm's complexity (measured in worst case comparisons) is O(N^2) where N = len(s). It is similar to having two nested for statements.

    This video does a great job explaining the above, and you know what they say, an image is worth 1000 words.

    0 讨论(0)
  • 2020-12-10 03:32
    def insertionsort(list):
        for i in range(1,len(list)):
            temp=list[i]
            j=i-1
            while temp<+list[j] and j>=0:
                list[j+1]=list[j]
                j=j-1
            list[j+1]=temp
        return list
    list=eval(raw_input('Enter a list:'))
    print insertionsort(list)
    

    This will help you.

    0 讨论(0)
  • 2020-12-10 03:36
    def insertion(x):
        for i in range(1, len(x)):
            while x[i - 1] > x[i] and i >= 0:
                x[i - 1], x[i] = x[i], x[i - 1]
                i -= 1
        return x
    

    Something like that

    0 讨论(0)
提交回复
热议问题