Sorting Algorithms, Part One

Inspired by a question from a programming interview, I’ve taken it upon myself to learn how to implement different sorting algorithms in Python. My goal is to:

  1. Learn a bit more about programming algorithms, and
  2. Get back into Python-coding shape.

The first algorithm I’ve coded up is a simple Straight Sort. It sorts a series of numbers like you’d sort a hand of cards: it picks the second number and sorts it with respect to the first, then picks the third number and places it where it should be with respect to the first two, and so on. It’s pretty fast for low numbers of integers, but slows down exponentially as the number of integers grows.

Here’s the actual code:

def straightSort(data): “““Takes a list of integers and returns a sorted list. Based on Straight Insertion method. Note: will not sort non-unique items!””” for item in data: currentIndex = data.index(item) for i in data[:currentIndex]: if data[currentIndex - 1] > item and currentIndex > 0: data[currentIndex] = data[currentIndex - 1] data[currentIndex - 1] = item currentIndex -= 1 return data

It’s pretty simple, but I feel I may have been writing C++ style code in Python, instead of writing Python-style code. Any suggestions?

Ron Toland @mindbat