September 26, 2011 Sorting and Searching Lists. Agenda Review quiz #3 Team assignment #1 due tonight...

Preview:

Citation preview

September 26, 2011

Sorting and Searching Lists

Agenda Review quiz #3 Team assignment #1 due tonight

One per team Arcade game Searching

Linear Binary

Sorting Selection Search

What else can we do with a List? What about a high score tracker for an

arcade game? What data needs to be stored? Is the data sorted in some way? Let’s try it out…

Movement Add info to lists

Linear Search – High Score

Examine each component in the list Similar to a checkout line

The line of customers is a list The checkout clerk processes each customer’s

purchase one at a time

Linear Search Algorithm – Searching for Highest ScoreSet largestIndex = 1

Set index = 1

Repeat for the length of L

if L[index] > L[largestIndex]

set largestIndex = index

index = index + 1

Print L[largestIndex]

Example in Scratch

Binary Search

Phonebook example Information must be sorted first!

How do we sort?

Sorting How can we sort the scores from the highest

score to the lowest score and the players alphabetically?

Selection Sort Find the largest number in the list Swap it with the item in the first position Repeat starting with the second element in the list

What do we need? Swap method Sort method

Selection Sort

Similar to a linear search Find the smallest (or largest) value and place

it in the first slot Repeat this for each position in the list

Animated example http://www.cs.oswego.edu/~mohammad/classes/

csc241/samples/sort/Sort2-E.html

Selection Sort – Players

Binary Search

Phonebook Look at the middle of the list If the value is larger than the item in the

middle of the list Look at the last half

Otherwise Look at the first half

Binary SearchRepeat until found = true or min > max

mid = max+min/2

if value > L[mid]

min = mid + 1

else if value < L[mid]

max = mid – 1

else

found = true

if found = false

mid = -1

print mid

Binary Search - BYOB

Recommended