Design and Analyis of Algorithms: Getting Started

Overview
Running code in your browser

Here is Python code for a swap routine, which our textbook uses periodically:

        
        l = [1, 2, 3]
        
        def swap(l, i, j): 
            temp = l[i]
            l[i] = l[j]
            l[j] = temp
        
        

Paste that code into the Python console below:

Python console

Hit return. Then type 'swap(l, 0, 2)' and hit return.
Then type 'l'.

You should see '[3, 2, 1]': you swapped element 0 and 2!

Now type in the following:

        def bubble_sort(l):
            for i in range(0, len(l) - 1):
                for j in range(len(l) - 1, i, -1):
                    if l[j] < l[j - 1]:
                        print("Swapping " + str(l[j]) + " and "
                                + str(l[j - 1]))
                        swap(l, j, j - 1)
            return l
    
Source Code

Java
Ruby
Go
Javascript
C++
Python
Clojure

For Further Study
Homework