Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1101: Programming Methodology Aaron Tan.

Similar presentations


Presentation on theme: "CS1101: Programming Methodology Aaron Tan."— Presentation transcript:

1 CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101x/ http://www.comp.nus.edu.sg/~cs1101x/ Aaron Tan

2 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 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 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 5 Insertion Sort (2/6) Example – pass 1 v 0 1 2 3 4 105716 Sorted region v 510716 Sorted region Where to insert v[1] in the sorted region to its left (v[0])?

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

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

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

9 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 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 11 Search result numbers 231759012 4438 012345678 8477 Unsuccessful Search: Successful Search: search( 45 ) search( 12 ) 4

12 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 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 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 512172338 4477 012345678 8490

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

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

17 17 Sequence of Successful Search (3/3) 512172338 4477 012345678 8490 search( 44 ) lowhighmid 0808 #1 44 == 44 4 5858 #2 6 highlow5 #3 mid 5 Successful Search!!

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

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

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

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

22 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 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 24 Comparing Sequential Search and Binary Search Array size NSequential Search N Binary Search log 2 N 883 16 4 100 7 1,000 10 10,000 14 1,000,000 20 1,000,000,000 30

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

26 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 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 2 1 2 1 x 0 0 y 2 1

28 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); 324324 array

29 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 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 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 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 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 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 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:  http://www.comp.nus.edu.sg/~cs1101x/3_ca/labs.html http://www.comp.nus.edu.sg/~cs1101x/3_ca/labs.html

36 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 37 This is Week 9  Next week?  Chapter 11 Type Details and Alternate Coding Mechanisms  Another mini programming test!

38 38 End of file


Download ppt "CS1101: Programming Methodology Aaron Tan."

Similar presentations


Ads by Google