Using Python to implement 8 sorting algorithms-insert Sort

Source: Internet
Author: User
Basic idea of inserting sort:

Each step inserts a record to be sorted by the size of its key value into the appropriate position in the previously sorted file until all is inserted.

Cases:

arr = [49,38,04,97,76,13,27,49,55,65], from the 2nd number as the key value, compares forward, as the previous number is large, is exchanged,

arr = [38,49,04,97,76,13,27,49,55,65], and then from the 3rd number as the key value, the forward comparison, the former large is exchanged,

arr = [38,04,49,97,76,13,27,49,55,65], then continue, arr = [04,38,49,97,76,13,27,49,55,65]

Note: In order to compare forward, because the previous array is ordered, so the current number is less than or equal to the key value, you can jump out of the forward comparison of the loop, the algorithm speed is significantly improved.

Code:

def insert_sort (lists):      #插入排序      count = Len (lists) for      I in range (1,count): #从第2个数起遍历          key = Lists[i]          j = i-1          while J >= 0:              if LISTS[J] > key:                  lists[j+1], lists[j] = lists[j], key              else:break  #当前一 If the number is less than or equal to key, jump out of loop              J-= 1      return lists
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.