Docsity

CISC 106 Lecture 17: Search and Sort for Shark & Goldfish Simulator, Study Guides, Projects, Research of Computer Science

Partial preview of the text

Download CISC 106 Lecture 17: Search and Sort for Shark & Goldfish Simulator and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

General Computer Science

for Engineers

CISC 106

Lecture 17

Roger Craig

Computer and Information Sciences

Lecture Overview

 Office hours today--> tomorrow

 Project 1

 Linear search vs. Binary search

 Selection sort

Functions

%Make the board. Make the shark and position the shark. %Calls play and makeBoard function [] = startShark(rows, cols) %Recursive function that implements top-level algorithm. %oldShark is a shark with the previous position. %Calls: print, plotBoard, getClosestGoldfish, moveToGoldfish, eatGoldfish function [] = play(board, shark, oldShark) %Goldfish disappears from board, shark moves into former goldfish location. %Calls: function [newBoard newShark] = eatGoldfish(board, goldfishCoords, shark) %Prints an ascii version of board at interpreter prompt, showing all %simulated items. function [] = print(board, shark) %Plots board, showing all simulated items. %Calls: plotSquare function [] = plotBoard(board, shark, oldShark)

Functions cont.

%Plots a single square on board. %Calls: patch function [] = plotSquare(row, col, color) %Shark moves one square at a time, horizontally or vertically, until %shark is adjacent to goldfish. Returns updated copy of shark. %Calls: isAdjacent, moveOneSquare, print, plotBoard function newShark = moveToGoldfish(board, goldfishCoords, shark) %Move shark one square closer to coords. New shark location must be a %legal, unoccupied square. %Calls: isLegalMove function [canMove newShark] = moveOneSquare(board, coords, shark) %Returns true iff board is empty at proposed position and position is %valid for this board. %Calls: function legal = isLegalMove(board, proposedMove)

Linear search vs. Binary Search

Linear search takes N iterations in the

worst case

Binary search takes log2(N) iterations

in the worst case

Selection Sort

One of the easiest ways to

sort

But computationally

inefficient for a big dataset

(see Chapman Chapter 5)

Selection sort pseudocode

In: unsorted array, array, of length n.

Out: sorted array, array.

Loop through from i = 0 to n-

minLoc = i

min = array[i]

Loop through from j = i+1 to n

if min > array[j] then

minLoc = j

min = array[j]

end inner loop

%swap the values at the ith %

%...position and the minLoc position

tmp = array[i]

array[i] = array[minLoc]

array[minLoc] = tmp

End outer loop

Return array

While not at end of array
find the minimum value from…
the current location (or loc) to the…
end of the array
swap the current loc with the min’s loc
End While
Return array

Number of steps?

Sum(N -1 + n-2 + n -3 + n -4 …. 1)

This is roughly n^2.

(The best sorting algorithms require

about n*log(n) )