Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Science and Object-Oriented Programming

Similar presentations


Presentation on theme: "Introduction to Computer Science and Object-Oriented Programming"— Presentation transcript:

1 Introduction to Computer Science and Object-Oriented Programming
Week 11

2 Tonight More Array Operations Sorting and Searching Potpourri
Test 2 Review Week 11

3 A Small Challenge Write the code for the swap method
In some class you have an instance variable int[] val and a method private void swap(int i, int j) that swaps the values in positions i and j Write the code for the swap method Week 11

4 How many assignments does it take to swap?
A Small Challenge private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } How many assignments does it take to swap? Week 11

5 Another Challenge Same set up What’s this method do?
private void mystery(int left, int right) { int temp = a[right]; for (int j = right-1; j >= left; j--) a[j] = a[j-1]; } a[left] = temp; Week 11

6 How many assignments are done?
Another Challenge private void mystery(int left, int right) { int temp = a[right]; for (int j = right; j > left; j--) a[j] = a[j-1]; } a[left] = temp; How many assignments are done? Week 11

7 Feeling Out of Sorts? Week 11

8 Sorting Data processing / information processing
one of the earliest computing domains often simple, repetitive calculation payroll, inventory, etc. Critical was the ability to store and search for info prepare reports Fundamental to this was sorting Week 11

9 Sorting Sorting was critical Much effort went into for reports
for more effective searching Much effort went into finding better ways to sort comparing ways to sort Week 11

10 To Understand Sorting An array of values
with positions/indices that we can separate into “regions” Criterion for ordering given two values either they are equal or one comes before the other in order [0] [1] [2] [3] [4]] 5 9 17 11 12 Week 11

11 In the to sort region, find the minimum and swap with next to fill
Selection Sort Simple sort Think of regions next to fill [0] sorted to search In the to sort region, find the minimum and swap with next to fill Week 11

12 Selection Sort 11 9 17 5 12 11 9 17 5 12 5 9 17 11 12 Ready for pass 1
to search Search for min 11 9 17 5 12 5 9 17 11 12 Ready for pass 2 to search Week 11

13 Selection Sort 5 9 17 11 12 Ready for pass 2 to search 5 9 17 11 12 Ready for pass 3 5 9 11 17 12 Ready for pass 4 5 9 11 12 17 Ready for pass 5 Week 11

14 In the sorted region, find the place to insert the next to place
Insertion Sort Simple sort Think of regions next to place [0] sorted In the sorted region, find the place to insert the next to place Week 11

15 Insertion Sort 11 9 17 5 12 11 9 17 5 12 9 11 17 5 12 Initial state
sorted 11 9 17 5 12 Begin first pass 1st pass begins at pos 1 to sort 9 11 17 5 12 Begin second pass 2nd pass begins at pos 2 sorted Sort the region by placing and shifting Week 11

16 Insertion Sort 9 11 17 5 12 5 9 11 17 12 5 9 11 12 17 Begin third pass
3rd pass begins at pos 3 Begin fourth pass 5 9 11 17 12 4th pass begins at pos 4 5 9 11 12 17 Final state Week 11

17 In the sorted region, find the place to insert the next to place
Bubble Sort Simple sort Think of regions next to place [0] sorted unsorted In the sorted region, find the place to insert the next to place Week 11

18 Bubble Sort Compare the first two elements of the array. If the first element is larger than the second Then swap them Otherwise, leave them alone. Repeat this step for the second and third element then the third and fourth and so on. At the end of the first pass the last number in the array is the largest. Repeat for as many times as elements in the array Week 11

19 Bubble Sort 11 9 17 5 12 11 9 17 5 12 9 11 5 12 17 Initial state
Begin first pass 1st pass compare pattern: 9 11 5 12 17 Begin second pass 2nd pass compare pattern: Week 11

20 Bubble Sort 9 5 11 12 17 5 9 11 12 17 5 9 11 12 17 Begin third pass
3rd pass compare pattern: 5 9 11 12 17 Begin forth pass 4th pass compare pattern: 5 9 11 12 17 Final state Week 11

21 Profiling 9 5 11 12 17 5 9 11 12 17 5 9 11 12 17 Begin forth pass
3rd pass compare pattern: 5 9 11 12 17 Begin forth pass 4th pass compare pattern: Begin third pass 5 9 11 12 17 Final state Week 11

22 Comparing Sort Approaches
Historically, sorting was Critical Costly Studied What is the efficiency of the sort algorithms? Which is the best to use? Approaches Profiling Algorithm analysis Week 11

23 Profiling Use a “stopwatch” approach
Use the system clock to get time of execution in milliseconds The steps Get CPU clock time (t1) Run sort method Get CPU clock time (t2) Sort time (approximately) is t2 – t1 Time numbers Week 11

24 Profiling Elements Bubble Selection Insertion 2,560 31 15 5,120 125 47
Sort time in milliseconds for various array sizes Elements Bubble Selection Insertion 2,560 31 15 5,120 125 47 20,480 1,969 875 563 81,920 31,391 14,047 9,125 Week 11

25 Analyzing Sort Algorithms
Analyze how many times each array element is “visited” during search. Number of visits for selection sort (n numbers): ½ n2 + 5/2 n – 3 As n gets bigger, fastest growing term is n2 So rest of equation can be ignored.

26 Analyzing Sort Algorithms
Selection sort considered O(n2) algorithm - this is called Big-Oh notation Selection sort, Bubble sort, and Insertion sort are all O(n2)algorithms

27 Searching When there are a large number of items to search
There are different strategies for finding a specific item: Ordered or not Where to look next

28 Linear Search A linear search looks through list from the beginning until it encounters the desired item. Very simple, yet very inefficient. If the list is sorted, the search process can end when a value greater than the one sought out is found. int foundIt = -1; for (int i = 0; i < array.length; i++) { if (array[i] == searchValue) foundIt = i; break; // out of for loop } // when done, foundIt holds position of item or –1 Linear search is O(?) algorithm

29 Binary Search A binary search assumes you start with a sorted list.
Algorithm: The list is divided in half to find the mid-point. At this mid-point, one of three states exist: You have found the item. The item is less than the mid-point. The item is greater than the mid-point. If the value sought is not found, divide the remaining space in half and find a new mid-point. Repeat until you find the item or run out of space to divide. Binary search is O(logn)

30 A View of Variables count  hgt1  score int count; Height hgt1;
count primitive value Height hgt1; hgt1 object reference int[] score; score array reference Week 11

31 A View of Variables 5 count hgt1 score count = 5; hgt1 = new Height();
primitive value hgt1 = new Height(); feet inches hgt1 object reference int[] score = new int[3]; [0] [1] [2] score array reference Week 11

32 A View of Variables 9 count hgt1 score count = 9; hgt1.setFeet(5);
primitive value hgt1.setFeet(5); feet 5 inches hgt1 object reference score[1] = 10; [0] [1] 10 [2] score array reference Week 11

33 A View of Variables 10 count hgt1 score count = count + 1;
primitive value this.inches = 4; feet 5 inches hgt1 object reference score[2] = score[1] - 1; [0] [1] 10 [2] 9 score array reference Week 11

34 So What Is An Array? An array has a name has a type has a length
and is a reference to a collection of indexed … values? variables? slots? Week 11

35 classes can have instance fields that are arrays
Variations classes can have instance fields that are arrays an instance of Gradebook “J. Doe” name [0] [1] 10 [2] 9 score Week 11

36 arrays can have class types
Variations arrays can have class types Height[] tall = new Height[3]; 5 10 feet inches [0] [1] [2] 6 4 feet inches tall[1] = new Height(5,10); tall[2] = new Height(6,4); Week 11

37 Some Examples On BlueJ Week 11

38 Array Algorithms You can calculate with numbers
You can manipulate Strings What can you do with arrays? count the elements count the elements matching a condition find element an element matching a condition calculate min, max, sum average, etc. and much more … Week 11

39 Array Lists Arrays have some limitations Array lists
While we don’t need to fill them They have a maximum number of elements We have to program the operations (except for ….????) Array lists Can grow and shrink as needed Provide useful methods Week 11

40 ArrayLists All element of same type
Must be a class type (not primitive type) Starts out empty Has a size (starts out zero) Week 11

41 Examples Constructing Adding Accessing
ArrayList<Customer> store1 = new ArrayList<Customer> (); // newly created list, size is 0 Adding store1.add( new Customer(“William Dodds”, )); // size is 1 now store1.add( new Customer(“Martha Shavers”, )); // size is 2 now Accessing Customer cust = store1.get(1); // retrieves second object int store1Size = store1.size(); // returns size (2) Customer newCust = new Customer(“Lee Cash”, ); store1.set(1, newCust); // overwrites Martha with Lee Week 11

42 Accessing Use get method Index starts at 0
BankAccount anAccount = accounts.get(2); gets the third element of the array list Bounds error if index is out of range Most common bounds error: int i = accounts.size(); anAccount = accounts.get(i); // Error Week 11

43 Adding Before add(i,a) Week 11

44 Removing remove removes an element at an index accounts.remove(i)
Week 11

45 Wrappers primitive types are not objects
so can’t use directly in ArrayLIst so Java has wrapper classes Week 11

46 Wrapper Class   ArrayList<Double> data = new ArrayList<Double>(); data.add(29.95); double x = data.get(0); Week 11

47 Wrapper Classes Are classes Start with cap
Each contains a single value of corresponding type Use where objects needed Week 11

48 Auto-Boxing Automatic conversion between
primitive types and the corresponding wrapper classes is automatic. Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95); double x = d; // auto-unboxing; same as double x = d.doubleValue(); Auto-boxing even works inside arithmetic expressions Double e = d + 1; Means: auto-unbox d into a double add 1 auto-box the result into a new Double store a reference to the newly created wrapper object in e Week 11

49 Auto-Boxing A recent feature of Java Automatic conversion between
primitive types corresponding wrapper class Double d = 29.95; Double d = new Double(29.95); double x = d; double x = d.doubleValue(); Double e = d + 1; Week 11

50 Enhanced For Loop Recent addition to Java Shortcut for a common loop
for (typevariable : collection) { statements } Week 11

51 Examples double[] data = new double[100];
… assume that array is then populated double sum = 0; for (double e : data) { sum = sum + e; } Week 11

52 Examples ArrayList<BankAccount> accounts =
new ArrayList<BankAccount>(); … assume that array list is then populated double sum = 0; for (BankAccount a : accounts) { sum = sum + a.getBalance(); } Week 11

53 Two-Dimensional Arrays
int[][] table = new int[2][3]; The array identified by table will have 2 rows (the row is the FIRST subscript) 3 columns (the column is the SECOND subscript). [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] Week 11

54 Examples table[0][0] = 22; table[0][1] = 1301; . . . table[1][2] = 43;
for (int i = 0; i < 2; ++i) for (int j = 0; j < 3; ++j) System.out.println(table[i][j]); Week 11

55 Self Check 7.1 What elements does the data array contain after the following statements? double[] data = new double[10]; for (int i = 0; i < data.length; i++) data[i] = i * i; Week 11

56 Answer: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, but not 100 Week 11

57 What do the following program segments print? Or, if there is an
Self Check 7.2 What do the following program segments print? Or, if there is an error, describe the error and specify whether it is detected at compile-time or at run-time. double[] a = new double[10]; System.out.println(a[0]); double[] b = new double[10]; System.out.println(b[10]); double[] c; System.out.println(c[0]); Week 11

58 Answer: a run-time error: array index out of bounds
a run-time error: array index out of bounds a compile-time error: c is not initialized Week 11


Download ppt "Introduction to Computer Science and Object-Oriented Programming"

Similar presentations


Ads by Google