CS1101: Programming Methodology Aaron Tan.

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

CSE Lecture 3 – Algorithms I
Multidimensional arrays Many problems require information be organized as a two- dimensional or multidimensional list Examples –Matrices –Graphical animation.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11: Sorting and Searching  Searching Linear Binary  Sorting.
Chapter 11 Sorting and Searching. Topics Searching –Linear –Binary Sorting –Selection Sort –Bubble Sort.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Searching and Sorting Copyright Prentice Hall (with modifications by Evan Korth)
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 11 Sorting and Searching.
 Last lesson  Arrays for implementing collection classes  Performance analysis (review)  Today  Performance analysis  Logarithm.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Analysis of Algorithm.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology Aaron Tan.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 10 Sorting and Searching.
Building Java Programs Chapter 13 Searching reading: 13.3.
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
Applications of Arrays (Searching and Sorting) and Strings
Chapter 19: Searching and Sorting Algorithms
Lecture 12. Searching Algorithms and its analysis 1.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
1 2. Program Construction in Java. 2.8 Searching.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
CS 162 Intro to Programming II Searching 1. Data is stored in various structures – Typically it is organized on the type of data – Optimized for retrieval.
SEARCHING. Vocabulary List A collection of heterogeneous data (values can be different types) Dynamic in size Array A collection of homogenous data (values.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Searching Course Lecture Slides 28 May 2010 “ Some things Man was never.
CSC 211 Data Structures Lecture 13
Chapter 14: Searching and Sorting
CS1101: Programming Methodology
Data Structure Introduction.
1 Section 2.1 Algorithms. 2 Algorithm A finite set of precise instructions for performing a computation or for solving a problem.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Searching and Sorting.
CS1101: Programming Methodology
CS1101: Programming Methodology
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Selection Sort Sorts an array by repeatedly finding the smallest.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Searching & Sorting.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Sorting and Searching. Searching  Problem definition: Given a value X, return the index of X in the array if such X exist. Otherwise, return NOT_FOUND(-1).
Lecture 9COMPSCI.220.FS.T Lower Bound for Sorting Complexity Each algorithm that sorts by comparing only pairs of elements must use at least 
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
CS1020 Data Structures and Algorithms I Lecture Note #2 Arrays.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Chapter 3: Sorting and Searching Algorithms 3.1 Searching Algorithms.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
CS1101: Programming Methodology Aaron Tan.
Using recursion for Searching and Sorting
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
COP 3503 FALL 2012 Shayan Javed Lecture 15
Chapter 7 Single-Dimensional Arrays
Searching & Sorting "There's nothing hidden in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting.
Searching and Sorting Arrays
Principles of Computing – UFCFA3-30-1
Presentation transcript:

CS1101: Programming Methodology Aaron Tan

2 This is Week 9  Week 8:  Chapter 7: OOP Additional Details (cont.)  About String  Exercises  Chapter 8: Software Engineering  Chapter 9: Classes with Class Members  Exercises  This week:  Exercises  Chapter 10 Arrays and ArrayList s  Exercises

3 Exercises  Please refer to BallV2.java and BallV2Driver.java  Have you completed the computeArea() method in MyRectangle.java?  Have you updated your MyRectangle.java to include area as another data member (instance variable)?

4 Insertion sort (1/6)  We have discussed Selection sort and Bubble sort. Let’s learn another basic sort: Insertion sort. Algorithm basis  On pass i, Insert v[i] into the correct position in the sorted region to its left: v[0]…v[i-1]. Example – pass 1 (assume n = 5)  Compare v[1] with v[0]  If v[1] < v[0], move v[1] to the front of v[0] (shifting needed)  The sorted region now consists of two elements: v[0] and v[1].

5 Insertion Sort (2/6) Example – pass 1 v Sorted region v Sorted region Where to insert v[1] in the sorted region to its left (v[0])?

6 Insertion Sort (3/6) Example – pass 2 v Sorted region v Sorted region Where to insert v[2] in the sorted region to its left (v[0].. v[1])?

7 Insertion Sort (4/6) Example – pass 3 v Sorted region v Sorted region Where to insert v[3] in the sorted region to its left (v[0].. v[2])?

8 Insertion Sort (5/6) Example – pass 4 v Sorted region v Sorted region Where to insert v[4] in the sorted region to its left (v[0].. v[3])? Sort completed!

9 Insertion Sort (6/6) An array of n elements requires n-1 passes in insertion sort. (This is the same for Selection sort and Bubble sort.) Try to code insertion sort yourself.  In inserting the element being examined into the sorted region, try to avoid using swaps. Instead, shift the affected elements to the right one place to make way for the incoming element that is to be inserted.

10 Searching  Another classic computer science problem Problem statement:  Given a search value X, return the index of X in the array if X is found. Otherwise, return -1.  We assume no duplicate value in the array.  If there are duplicate values, we need to define which index to be returned.  Two algorithms  Sequential search (also called linear search)  Binary search (applicable for sorted array) – much faster

11 Search result numbers Unsuccessful Search: Successful Search: search( 45 ) search( 12 ) 4

12 Sequential Search (or Linear Search) Search the array from the first to the last position in linear progression. public static int linearSearch(int[] numbers, int searchValue) { for (int i=0; i<number.length; i++) { if (numbers[i] == searchValue) return i; } return -1; // not found }

13 Cohesion (again) Note that the linearSearch() method does not display the index of the found element in the array, nor does it even display any message on whether the search value is found or not. Instead, it returns the index of the first matching element, or –1 if the search value is not found. This follows the principle of cohesion – a method should do a single task. In this case, it should leave it to the caller to decide if any message needs to be displayed.

14 Binary search If the array is sorted, then we can apply the binary search technique. The basic idea is straightforward. First search the value X in the middle position of the array.  If X is the middle value, then found.  If X is less than the middle value, then search the middle of the left half next.  If X is greater than the middle value, then search the middle of the right half next. Continue in this manner. numbers

15 Sequence of Successful Search (1/3) search( 44 ) lowhighmid 0808 #1 high low 38 < 44 low = mid+1 = 5 mid 4

16 Sequence of Successful Search (2/3) search( 44 ) lowhighmid 0808 #1 44 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2

17 Sequence of Successful Search (3/3) search( 44 ) lowhighmid 0808 #1 44 == #2 6 highlow5 #3 mid 5 Successful Search!!

18 Sequence of Unsuccessful Search (1/4) search( 45 ) lowhighmid 0808 #1 high low 38 < 45 low = mid+1 = 5 mid 4

19 Sequence of Unsuccessful Search (2/4) search( 45 ) lowhighmid 0808 #1 45 < 77 high = mid-1=5 4 mid 6 highlow 5858 #2

20 Sequence of Unsuccessful Search (3/4) search( 45 ) lowhighmid 0808 #1 44 < #2 6 highlow5 #3 mid 5 low = mid+1 = 6

21 Sequence of Unsuccessful Search (4/4) search( 45 ) lowhighmid 0808 # #2 65 #3 5 highlow 6565 #4 Unsuccessful Search low > high no more elements to search

22 Binary Search Routine public static int binarySearch(int[] numbers, int searchValue) { int low = 0; int high = numbers.length – 1; int mid = (low + high) / 2; while (low <= high && numbers[mid] != searchValue) { if (numbers[mid] < searchValue) low = mid + 1; else // (numbers[mid] > searchValue) high = mid - 1; mid = (low + high) / 2; // next midpoint } if (low > high) { mid = -1; } return mid; }

23 Binary Search Performance Successful Search  Best Case: 1 comparison  Worst Case: log 2 N comparisons Unsuccessful Search  Best Case = Worst Case: log 2 N comparisons Since the portion of an array to search is cut into half after every comparison, we compute how many times the array can be divided into halves. After K comparisons, there will be N/2 K elements in the list. We solve for K when N/2 K = 1, deriving K = log 2 N.

24 Comparing Sequential Search and Binary Search Array size NSequential Search N Binary Search log 2 N , , ,000, ,000,000,000 30

25 Chapter 10 Let’s continue with the rest of Chapter 10.

26 Common mistake (1/2) When you have an array of objects, it’s very common to forget to instantiate the array’s objects. Programmers often instantiate the array itself and then think they’re done – that leads to “java.lang.NullPointerException”.

27 Common mistake (2/2) Point[] array = new Point[3]; for (int i=0; i<array.length; i++) { array[i].setLocation(1,2); } array null There are no objects referred to by array[0], array[1], and array[2]! Point[] array = new Point[3]; for (int i=0; i<array.length; i++) { array[i] = new Point(); array[i].setLocation(1,2); } Corrected code: array 0 x 0 y 0 x 0 y x 0 0 y 2 1

28 Rows with different lengths (1/2) It is possible to create 2D array where rows have different lengths. int[][] array = { {1,3,6}, {4,2}, {5,1,8,2} }; System.out.println(arr[0].length); System.out.println(arr[1].length); System.out.println(arr[2].length); array

29 Rows with different lengths (2/2) Code to process such array. int[][] array = { {1,3,6}, {4,2}, {5,1,8,2} }; for (int i=0; i<array.length; i++) { for (int j=0; j<array[i].length; j++) { System.out.print(array[i][j] + " "); } System.out.println(); }

30 Matrices A two-dimensional array where all rows have the same length is sometimes known as a matrix because it resembles that mathematical concept. A matrix A with m rows and n columns is represented mathematically in the following manner. Note that in implementing the matrix as an array in Java, the row number and column number start at 0 instead of 1.

31 Matrix Addition (1/2) To add two matrices, both must have the same number of rows, and the same number of columns. To compute C = A + B, where A, B, C are matrices  c i,j = a i,j + b i,j Example on 3  3 matrices:

32 Matrix Addition (2/2) public static int[][] add(int[][] arrA, int[][] arrB) { // determine number of rows in solution int m = arrA.length; // determine number of columns in solution int n = arrB[0].length; // create the array to hold the sum int[][] arrC = new int[m][n]; // compute the matrix sum row by row for (int i = 0; i < m; ++i) { // produce the current row for (int j = 0; j < n; ++j) { arrC[i][j] = arrA[i][j] + arrB[i][j]; } return arrC; }

33 Matrix Multiplication (1/2) To multiply two matrices A and B, the number of columns in A must be the same as the number of rows in B. The resulting matrix has same number of rows as A and number of columns as B. For example, multiplying a 4  5 matrix with a 5  3 matrix gives a 4  3 matrix.

34 Matrix Multiplication (2/2) To compute C = A  B, where A, B, C are matrices  c i,j = (a i,1  b 1,j ) + (a i,2  b 2,j ) (a i,n  b n,j )  c i,j is sum of terms produced by multiplying the elements of A’s row i with B’s column j. Example on 3  3 matrices:

35 Exercises  Download Matrices.java and complete the matrixProduct() method.  Try last year’s lab #7 exercises:  Sudoku  Rabbit Jumps  Polygon  Go to course website, “Labs” page to retrieve last year’s lab write-ups: 

36 Announcement/Reminder  Lab #4  Released: 14 October (Tuesday), 2359 hr.  Deadline: 22 October (Wednesday), 2359 hr.  Identical codes  Please do not share codes for your lab assignments!  Last year’s lab assignments  They are now on the course website, under “CA”, “Labs”, for your own practice.

37 This is Week 9  Next week?  Chapter 11 Type Details and Alternate Coding Mechanisms  Another mini programming test!

38 End of file