Docsity

Data Structures Lecture 16: Selection Sort, Bubble Sort, and Insertion Sort, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
1. The Dictionary implementation using open-address hashing was the OpenAddrHashDict class in lab7.zip.
from entry import Entry
class OpenAddrHashDict(object):
EMPTY = None # class variables shared by all objects of the class
DELETED = True
def __init__(self, capacity = 8, hashFunction = hash,
linear = True):
self._table = [OpenAddrHashDict.EMPTY] * capacity
self._size = 0
self._hash = hashFunction
self._homeIndex = -1
self._actualIndex = -1
self._linear = linear
self._probeCount = 0
def __getitem__(self, key):
"""Returns the value associated with key or
returns None if key does not exist."""
if key in self:
return self._table[self._actualIndex].getValue()
else:
return None
def __delitem__(self, key):
"""Removes the entry associated with key."""
if key in self:
self._table[self._actualIndex] = OpenAddrHashDict.DELETED
self._size -= 1
def __setitem__(self, key, value):
"""Inserts an entry with key/value if key does not exist or
replaces the existing value with value if key exists."""
entry = Entry(key, value)
if key in self:
self._table[self._actualIndex] = entry
else:
self._table[self._actualIndex] = entry
self._size += 1
def __contains__(self, key):
"""Return True if key is in the dictionary; return False otherwise"""
entry = Entry(key, None)
self._probeCount = 0
# Get the home index
self._homeIndex = abs(self._hash(key)) % len(self._table)
rehashAttempt = 0
index = self._homeIndex
# Stop searching when an empty cell is encountered
while rehashAttempt < len(self._table):
self._probeCount += 1
if self._table[index] in (OpenAddrHashDict.EMPTY,OpenAddrHashDict.DELETED):
self._actualIndex = index
return False
elif self._table[index] == entry:
self._actualIndex = index
return True
# Calculate the index and wrap around to first position if necessary
rehashAttempt += 1
if self._linear:
index = (self._homeIndex + rehashAttempt) % len(self._table)
else: # Quadratic probing
index = (self._homeIndex + (rehashAttempt ** 2+ rehashAttempt) // 2) % len(self._table)
return False # An empty cell is found, so key not found
def __len__(self):
return self._size
def __str__(self):
resultStr = "{"
for item in self._table:
if not item in (OpenAddrHashDict.EMPTY,OpenAddrHashDict.DELETED):
resultStr = resultStr + " " + str(item)
return resultStr + " }"
def __iter__(self):
"""Iterates over the keys of the dictionary"""
a) Complete the
__iter__
method.
Data Structures Lecture 16 Name:__________________
Lecture 16 Page 1
Docsity.com
pf3
pf4

Partial preview of the text

Download Data Structures Lecture 16: Selection Sort, Bubble Sort, and Insertion Sort and more Study notes Data Structures and Algorithms in PDF only on Docsity!

  1. The Dictionary implementation using open-address hashing was the from entry import Entry OpenAddrHashDict class in lab7.zip. class OpenAddrHashDict(object):EMPTY = NoneDELETED = True # class variables shared by all objects of the class def init(self, capacity = 8, hashFunction = hash,self._table = [OpenAddrHashDict.EMPTY] * capacityself._size = 0linear = True): self._hash = hashFunctionself._homeIndex = -1self._actualIndex = -1self._linear = linear def getitem(self, key):self._probeCount = 0"""Returns the value associated with key or returns None if key does not exist."""if key in self:else:return self._table[self._actualIndex].getValue() def delitem(self, key):"""Removes the entry associated with key."""return None if key in self:self._table[self._actualIndex] = OpenAddrHashDict.DELETEDself._size -= 1 def setitem(self, key, value):"""Inserts an entry with key/value if key does not exist orentry = Entry(key, value)replaces the existing value with value if key exists.""" if key in self:else:self._table[self._actualIndex] = entryself._table[self._actualIndex] = entry def contains(self, key):"""Return True if key is in the dictionary; return False otherwise"""self._size += 1 entry = Entry(key, None)self._probeCount = 0# Get the home indexself._homeIndex = abs(self._hash(key)) % len(self._table) rehashAttempt = 0index = self._homeIndex# Stop searching when an empty cell is encountered while rehashAttempt < len(self._table):self._probeCount += 1if self._table[index] in (OpenAddrHashDict.EMPTY,OpenAddrHashDict.DELETED):self._actualIndex = index elif self._table[index] == entry:return Falseself._actualIndex = indexreturn True # Calculate the index and wrap around to first position if necessaryrehashAttempt += 1if self._linear:index = (self._homeIndex + rehashAttempt) % len(self._table) return Falseelse:index = (self._homeIndex + (rehashAttempt ** 2+ rehashAttempt) // 2) % len(self._table)^ # Quadratic probing # An empty cell is found, so key not found def len(self):def str(self):return self._size resultStr = "{"for item in self._table:if not item in (OpenAddrHashDict.EMPTY,OpenAddrHashDict.DELETED):resultStr = resultStr + " " + str(item) def iter(self):return resultStr + " }""""Iterates over the keys of the dictionary""" a) Complete the iter method.
  1. All  the simple sort outer loop s consist of two nested loops where: keeps track of the dividing line between the sorted and unsorted part with the sorted part growing by one in size each iteration of the outer loop.  the inner loop's job is to do the work to extend the sorted part's size by one. Initially, the sorted part is typically empty. Selection sort is an example of a simple sort. Selection sort’s inner loop scans the unsorted part of the list to find the The simple sorts differ in how their inner loops perform their job. maximum item. The maximum item in the unsorted part is then exchanged with the last unsorted item to extend thesorted part by one item. At the start of the first iteration of the outer loop, initial list is completely unsorted:

0 1 2 Unsorted Part 3 4 5 6 7 Empty Sorted Part 8

The inner loop scans the unsorted part and determines that the index of the maximum item, maxIndex = 4.

Unsorted Part^ Sorted Part

After the inner loop (but still inside the outer loop), the item at maxIndex is exchanged with the item^ maxIndex = 4^ lastUnsortedIndex = 8

at lastUnsortedIndex. Thus, extending the Sorted Part of the list by one item.

Unsorted Part^ Sorted Part

a) Write the code for the outer loop^ maxIndex = 4^ lastUnsortedIndex = 8

b) Write the code for the inner loop to scan the unsorted part of the list to determine the index of the maximum item

c) Write the code to exchange the list items at positions maxIndex and lastUnsortedIndex.

d) What is the big-oh notation for selection sort?

  1. Another simple sort is called insertion sort. Recall that in a simple sort:  the outer loop keeps track of the dividing line between the sorted and unsorted part with the sorted part growing by one in size each iteration of the outer loop.  the inner loop's job is to do the work to extend the sorted part's size by one. After several iterations of insertion sort’s outer loop, a list might look like:

10 20 35 40 45 60 25 50 90 0 1 Sorted Part 2 3 4 5 6 7 8 Unsorted Part

In insertion sort the inner-loop takes the "first unsorted item" (25 at index 6 in the above example) and "inserts" itinto the sorted part of the list "at the correct spot." After 25 is inserted into the sorted part, the list would look like:

10 20 25 35 40 45 60 50 90 0 1 Sorted Part 2 3 4 5 6 7 8 Unsorted Part

Code for insertion is given below: def insertionSort(myList): """Rearrangesfor firstUnsortedIndex the items inin range(1,len(myList)):myList so they are in ascending order""" itemToInserttestIndex = firstUnsortedIndex= myList[firstUnsortedIndex] - 1 whilemyList[testIndex+1]testIndex testIndex = >=testIndex 0 and =myList[testIndex] myList[testIndex]- 1 > itemToInsert: #myList[testIndex Insert the itemToInsert + 1] = itemToInsert at the correct spot a) What is the purpose of the testIndex >= 0 while-loop comparison?

b) What initial arrangement of items causes the is the overall worst-case performance of insertion sort? c) What is the worst-case Ο ( ) notation for the number of item moves?

d) What is the worst-case Ο ( ) notation for the number of item comparisons? e) What initial arrangement of items causes the is the overall best-case performance of insertion sort?

f) What is the best-case Ο ( ) notation for insertion sort?