Spring 2012 CSCI 220 Week 12

Linear Search
def find_item(mylist,item): for it in mylist: if it == item: return it   return None

print(find_item(["one","two","three"],"two"))

Insertion Sort
Description: http://en.wikipedia.org/wiki/Insertion_sort

Though python’s in-built list/array type provides sort function, this demonstrates how the Insertion Sort algorithm works.

import sys

def InsertionSort(array): i = 0 j = 0 n = len(array) for j in range(n): key = array[j] i = j - 1 while (i >= 0 and array[i] > key): array[i + 1] = array[i] i = i -1 array[i + 1] = key

def PrintArray(array): for x in range(len(array)): print(str(array[x]) + " ",end="") print

def TestIntegerArray: iarr = [10,3,8,1,99,5,-1] PrintArray(iarr) InsertionSort(iarr) PrintArray(iarr)

def TestStringArray: sarr = ["Delhi","Sydney","California","Singapore"] PrintArray(sarr) InsertionSort(sarr) PrintArray(sarr)

if __name__ == "__main__": TestIntegerArray TestStringArray

Bubble Sort
Description: http://en.wikipedia.org/wiki/Bubble_sort

def main: array = [1, 7, 4, 9, 4, 7, 2, 3, 0, 8] print("Before sort:-") print(array) bubbleSort(array) print("After sort:-") print(array) def bubbleSort(array): swapHappened = True while swapHappened: swapHappened = False for x in range(0, len(array)-1): if array[x] > array[x+1]: # Swap data array[x], array[x+1] = array[x+1], array[x] swapHappened = True main

Selection Sort
Description: http://en.wikipedia.org/wiki/Selection_sort


 * 1) sort.py
 * 2)    Implementation of selection sort.
 * 3)    Author: Zelle (p. 444).

def selSort(nums): # sort nums into ascending order n = len(nums) # for each position in the list (except the very last) for front in range(n-1): # find the smallest item in nums[bottom]..nums[n-1] # ("mp" seems to mean "position of the minimum") mp = front                    # bottom is smallest initially for i in range(front+1,n):    # look at each position if nums[i] < nums[mp]:     # this one is smaller mp = i                 #   remember its index

# swap smallest item to the bottom temp = nums[mp] nums[mp] = nums[front] nums[front] = temp

Binary Search
def biSearch(x, nums): foundPos = -1 low = 0 high = len(nums) - 1 count = 0 while foundPos == -1 and low <= high: mid = (low + high) // 2 # print added for instructional purposes print ("low =",low,"high =",high,"mid =", mid) if x == nums[mid]: foundPos = mid elif x > nums[mid]: low = mid + 1 else: high = mid - 1 count = count + 1 print ("\nNumber iterations: " + str(count)) print ("After loop") print ("low =",low,"high =",high,"mid =", mid) return foundPos

Overriding Comparison Function
object.__cmp__(self, other)

Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. If no __cmp__, __eq__ or __ne__ operation is defined, class instances are compared by object identity (“address”). See also the description of __hash__ for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by __cmp__ has been removed since Python 1.5.)