COMP 14 Introduction to Programming Mr. Joshua Stough April 4, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.

Slides:



Advertisements
Similar presentations
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Advertisements

Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
Sorting I Chapter 8 Kruse and Ryba. Introduction Common problem: sort a list of values, starting from lowest to highest. –List of exam scores –Words of.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 9A Sorting (Concepts)
Visual C++ Programming: Concepts and Projects
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
COMP 10 Introduction to Programming Mr. Joshua Stough October 29, 2007.
COMP 14 Introduction to Programming Miguel A. Otaduy June 4, 2004.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
COMP 14: Sorting June 14, 2000 Nick Vallidis. Announcements zP4 is due today!
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
COMP 14 Introduction to Programming Mr. Joshua Stough March 30, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Searching and Sorting Arrays
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Aalborg Media Lab 15-Jul-15 Polymorphism Lecture 12 Chapter 9.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 8 ARRAYS Continued
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 Arrays 2: Sorting and Searching Admin. §1) No class Thursday. §2) Will cover Strings next Tuesday. §3) Take in report. §4) Hand out program assignment.
Chapter 11 Arrays Continued
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 19, 2005.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
CSCI 51 Introduction to Programming March 12, 2009.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Data Structures Arrays and Lists Part 2 More List Operations.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
CSCI 51 Introduction to Programming March 10, 2009.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
1 compares each element of the array with the search key. works well for small arrays or for unsorted arrays works for any table slow can put more commonly.
Prof. U V THETE Dept. of Computer Science YMA
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
Chapter 9: Sorting and Searching Arrays
16 Searching and Sorting.
Lecture 14 Searching and Sorting Richard Gesick.
Introduction to Search Algorithms
Recitation 13 Searching and Sorting.
Chapter 13: Searching and Sorting
Arrays … The Sequel Applications and Extensions
Describing algorithms in pseudo code
Outline Late Binding Polymorphism via Inheritance
Lecture 11 Searching and Sorting Richard Gesick.
Standard Version of Starting Out with C++, 4th Edition
Searching and Sorting 1-D Arrays
Principles of Computing – UFCFA3-30-1
Sorting Chapter 8.
Sorting and Searching -- Introduction
Principles of Computing – UFCFA3-30-1
Module 8 – Searching & Sorting Algorithms
Arrays.
Presentation transcript:

COMP 14 Introduction to Programming Mr. Joshua Stough April 4, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218

Program 5 Announcements "java.awt.Color.GREEN unrecognized" error –see Blackboard announcement –re-download BlackjackUI and BlackjackApplet Applet works, but cards don't appear –see Blackboard announcement –copy img folder over to your webspace –change IMG_URL to specify the img folder in your webspace –re-compile and copy BlackjackApplet.class over to your webspace

COMP 14 Rest of Semester Today (4/5) –searching and sorting Wed (4/7) –applets, HTML, and GUIs Mon (4/12) –computer graphics Wed (4/14) –networking Mon (4/19) –data structures Wed (4/21) –review for Final Exam

Declaration vs. Instantiation public class Dice { private Die[] dice; // declaration public Dice(int numDice) { dice = new Die[numDice]; // instantiation for (int i=0; i<dice.length; i++) { dice[i] = new Die(); } NOT // declaration and instantiation Die[] dice = new Die[numDice]; creates a new local variable called dice

Declaration vs. Instantiation public class Dice { private Die[] dice; public Dice(int numDice) { dice = new Die[numDice]; for (int i=0; i<dice.length; i++) { dice[i] = new Die(); } dice this face 3

Declaration vs. Instantiation public class Dice { private Die[] dice; public Dice(int numDice) { Die[] dice = new Die[numDice]; for (int i=0; i<dice.length; i++) { dice[i] = new Die(); } dice this dice face 3

Use the debugger in jGRASP! Declaration vs. Instantiation Set a breakpoint Compile in debug mode Press instead of Step through the program and look at the created variables

Writing Test Programs Die class –constructor - takes no parameters –getFace - returns the die's face value as int –roll - takes no parameters, returns nothing, rolls the die Tests –create two Die objects –roll both Die objects –print the face value of both Die objects Die die1 = new Die(); Die die2 = new Die(); die1.roll(); die2.roll(); System.out.println ("die1: " + die1.getFace()); System.out.println ("die2: " + die2.getFace());

DieTester.java public class DieTester { public static void main (String[] args) { Die die1 = new Die(); Die die2 = new Die(); die1.roll(); die2.roll(); System.out.println ("die1: " + die1.getFace()); System.out.println ("die2: " + die2.getFace()); }

Writing Test Programs Dice class –constructor - takes an int parameter (number of dice) –roll - takes no parameters, returns nothing, rolls all of the dice –getNumDie - takes no parameters, returns the number of dice –getDie - takes an int parameter (position), returns the Die at that position –toString - takes no parameters, returns String of all of the dice's face values

Writing Test Programs Tests –create a Dice object with 3 dice and another Dice object with 7 dice –roll all of the dice –print the 3-dice Dice object –print the 7-dice Dice object –print the face value of the 3rd die in the 7-dice Dice object Dice dice3 = new Dice(3); Dice dice7 = new Dice(7); dice3.roll(); dice7.roll(); System.out.println ("3 dice: " + dice3); System.out.println ("7 dice: " + dice7); System.out.println ("3rd die: " + dice7.getDie(2).getFace());

DiceTester.java public class DiceTester { public static void main (String[] args) { Dice dice3 = new Dice(3); Dice dice7 = new Dice(7); dice3.roll(); dice7.roll(); System.out.println ("3 dice: " + dice3); System.out.println ("7 dice: " + dice7); System.out.println ("3rd die: " + dice7.getDie(2).getFace()); }

Finding Pairs How do you pick which ones are pairs? Remember, a computer can only compare two things at a time. How do you explain to a small child (or a computer) how to pick which ones are pairs?

Finding Pairs ind1ind2 Does Die at ind1 equal Die at ind2? int len = dice.getNumDice(); for (int ind1 = 0; ind1<len-1; ind1++) { // save face value of Die at ind1 for (int ind2 = ind1+1; ind<len; ind2++) { // save face value of Die at ind2 // compare face values -- if match -> print } length of array? 5

Equality Die die1 = dice.getDie(ind1); Die die2 = dice.getDie(ind2); if (die1.getFace() == die2.getFace()) if (die1.equals(die2)) public boolean equals (Die otherDie) { if (getFace() == otherDie.getFace()) { return true; } return false; } in Die class

BlackjackUI What's going on behind the scenes in Program 5? We'll look at user interface code (how things are drawn on the screen) on Wednesday What happens when buttons are pressed?

Deal and Quit Buttons DealQuit dealButtonPressed();System.exit(0);

dealButtonPressed Method Initializes the hand –calls BlackjackGame.setupNewHand Draws blank cards Draws the player's cards –calls BlackjackGame.getPlayerHand –calls getNumCards and getCard in Hand class Draws the player's points –calls BlackjackGame.getPlayerHand –calls BlackjackGame.calcPoints with Hand parameter

dealButtonPressed (cont.) Changes the Deal button to Hit button Enables the Stand button Changes the instructions Calls BlackjackGame.playerCanHit to see if player can add more cards If player can't add more cards, calls playerDone method (in BlackjackUI class) –reset instructions –reset buttons

Hit and Stand Buttons HitStand hitButtonPressed();standButtonPressed();

standButtonPressed Calls playerDone method –reset instructions –reset buttons

hitButtonPressed Deals a new card to the player –calls BlackjackGame.addPlayerCard Draws the new card –calls BlackjackGame.getPlayerHand –calls getCard in Hand class Updates the player's points –calls BlackjackGame.getPlayerHand –calls BlackjackGame.calcPoints with Hand parameter Calls BlackjackGame.playerCanHit to see if player can add more cards If the player can't add any more cards, calls playerDone method

New Stuff Searching arrays for a particular value –reference: Ch 10 (pgs , ) Sorting arrays –makes searching for a particular value easier (and quicker) –reference: Ch 10 (pgs )

Searching Arrays Find one particular element in an array of many elements Find several particular elements in an array of many elements Complexity (How Long To Search?) –find a parking space - linear –look up a word in a dictionary - complex 500K+ words in OED – search - very complex over 3 trillion web pages

Linear Searching Given a test value and a list of values –list can be ordered or unordered –loop through the list repeatedly ask: Is this a match? quit when the answer is yes (use break stmt) –if you finish all items, there is no match Inefficient –worst time to search is ~ length –average time to search is ~ length/2 Relatively easy to program

// Linear search of unordered list of integers // unordered list int[] list = {17, 14, 9, 23, 18, 11, 62, 47, 33, 88}; // look for this value in the list int searchFor = 33; // Loop thru list until we find match int foundAt = -1; // where found (default) for (int index = 0; index < list.length; index++) { if (list[index] == searchFor) { foundAt = index; break;// jump out of the loop } // foundAt is now index of item “searchFor” // or -1 if not found

// Linear search of unordered list of Strings // unordered list String[] list = {“Bart”, “Homer”, “Marge”, “Lisa”, “Maggie”, “Millhouse”}; // look for this value in the list String searchFor = “Maggie”; // Loop thru list until we find match int foundAt = -1; // where found (default) for (int index = 0; index < list.length; index++) { if (list[index].equals(searchFor)) { foundAt = index; break;// jump out of the loop } // foundAt is now index of item “searchFor” // or -1 if not found

Binary Search Requires ordered (sorted) list Set searchRange to the entire list Repeat: –pick a “test value” in the middle of searchRange –if test value == value searching for Stop! –if test value > value searching for searchRange = lower half of searchRange –if test value < value searching for searchRange = upper half of searchRange

Example Looking for 46 Trial

Notes on Binary Searches List must be ordered (sorted) –can maintain a list in ordered fashion Much more efficient than linear –in example, took 3 iterations instead of 13 –time ~ log 2 (listLength) –linear worst case ~ listLength average ~ listLength/2 –for 100K words: 17 iterations versus 50,000 More complex to program

Searching Things To Know Be able to recognize and write a linear search Understand its pros and cons Know the concepts of a Binary Search

Questions How many comparisons are needed to determine if the following items are in the list of 10 items? linear searchbinary searchnumber (49, 10, 17) (49, 85, 92, 98) (49, 10, 2) (3, if know list sorted)

Sorting Put elements of an array in some order –alphabetize names –order grades lowest to highest Two simple sorting algorithms –selection sort –insertion sort

Selection Sort Sorts by putting values directly into their final, sorted position For each value in the list, the selection sort finds the value that belongs in that position and puts it there

Selection Sort General Algorithm Scan the list to find the smallest value Exchange (swap) that value with the value in the first position in the list Scan rest of list for the next smallest value Exchange that value with the value in the second position in the list And so on, until you get to the end of the list

Selection Sort At Work SORTED!

Selection Sort Sorts in ascending order Can be changed to sort in descending order –look for max instead of min

Insertion Sort Like we’d actually sort things Insert each new item into an already sorted list Each unsorted element is inserted at the appropriate spot in the sorted subset until the list is ordered

Insertion Sort General Algorithm Sort the first two values (swap, if necessary) Repeat: –insert list’s next value into the appropriate position relative to the first ones (which are already sorted) Each time insertion made, number of values in the sorted subset increases by one Other values in array shift to make room for inserted elements

Insertion Sort At Work SORTED!

Insertion Sort Outer loop controls the index in the array of the next value to be inserted Inner loop compares the current insert value with values stored at lower indexes Each iteration of the outer loop adds one more value to the sorted subset of the list, until the entire list is sorted

Bubble Sort "bubble" –largest values bubble to the end –smallest values sink to the beginning Idea –go through the list and swap neighboring items if needed Pros –easy to understand and code Cons –horribly inefficient (listLength 2 )

Bubble Sort At Work SORTED!

Sort Implementations All three use double (nested) loops Selection and insertion –an outer loops scans all elements –an inner loop scans and switches/inserts as needed Bubble –an outer loop repeats until no swaps are needed –an inner loops scans and swaps as needed

Sorting Things To Know Be able to recognize and follow an insertion sort, selection sort, and bubble sort Understand their pros and cons Know that many other sorts exist with varying efficiency and programming difficulty Sorting animations (in Java of course!)

Question Given the operation of the following sort, identify the type of sort (selection, insertion, or bubble) original pass 1 pass 2 pass 3 pass 4 pass 5 SORTED

Question Given the operation of the following sort, identify the type of sort (selection, insertion, or bubble) original pass 1 pass 2 pass 3 pass 4 SORTED

Sorting Things Other Than Numbers characters –same as integers (compare with ) Strings –use the built-in compareTo method Other Objects –we write a compareTo method –use the compareTo method

Next Time in COMP 14 Discussion of Program 6 Java applets HTML GUIs –how is the Blackjack user interface built? Reading Assignment (last one!): –Chapter 6 (pgs ) –skim Chapter 13 (pgs )