How to Make an Insertion Sort in Python

Python is an ideal programming language for beginners due to its natural language syntax, easy-to-follow indented code and flexible data types that are not interpreted until needed. When programming in Python, you may need to sort data. An insertion sort is a basic sort where Python starts at the beginning of an array and sorts through it one element at a time. Elements are sorted relative to each other during each iteration.

Instructions

    • 1

      Access your Python editor, and open your program.

    • 2

      Define the insertion sort routine. For example, define the insertion sort for sorting student test scores:

      def InsertionSort (scores)

    • 3

      Create the loop to sort through the array of scores. For example, type:

      for n in range (1, len(scores)):
      key = scores [n]
      i = n -1
      while (i > = 0) and (scores [1] > key) :
      scores [ i+1] = scores [ i ]
      i = i -1
      scores [ i +1] = key

    • 4

      Save your program and test it. Continuing the example, type the following and pressing "Enter."

      TestScores = [86, 55, 92, 67, 75, 83, 95 ]

    • 5

      Call the insertion sort routine by typing the following and pressing "Enter."

      InsertionSort (TestScores)

      Python sorts the list of test scores in ascending order. In this example, Python returns:

      [ 55, 67, 75, 83, 86, 92, 95 ]

Related Searches:

References

Comments

Related Ads

Featured