Introduction to Computer Science and Object-Oriented Programming

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7 Arrays and Array Lists. Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the.
Chapter 7 – Arrays.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Java Programming Week 6: Array and ArrayList Chapter 7.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ARRAYLIST Collections of Data. ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has.
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
Chapter 11 Arrays Continued
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
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.
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,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays. Array: Sequence of values of the same type Construct array: Store in variable of type double[ ] new double[10] double[] data = new double[10];
Searching Topics Sequential Search Binary Search.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Chapter 16: Searching, Sorting, and the vector Type
Chapter 7 – Arrays and Array Lists
Data Structures I (CPCS-204)
Principles of Computer Science I
Arrays.
Lecture 14 Searching and Sorting Richard Gesick.
Computer Programming BCT 1113
CSC 222: Object-Oriented Programming
7.6 Common Array Algorithm: Filling
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Teach A level Computing: Algorithms and Data Structures
Topic 14 Searching and Simple Sorts
Searching and Sorting Linear Search Binary Search ; Reading p
Algorithm design and Analysis
Introduction to Programming
Chapter 8 Slides from GaddisText
Lecture 11 Searching and Sorting Richard Gesick.
Review of Arrays and Pointers
Searching and Sorting 1-D Arrays
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
24 Searching and Sorting.
Data Structures (CS212D) Week # 2: Arrays.
Topic 14 Searching and Simple Sorts
Sorting "There's nothing 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 Hat, Harry Potter.
Arrays Week 2.
Sum this up for me Let’s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
Module 8 – Searching & Sorting Algorithms
Arrays.
Presentation transcript:

Introduction to Computer Science and Object-Oriented Programming Week 11

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

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

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

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

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

Feeling Out of Sorts? Week 11

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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

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)

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

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

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

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

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

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

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

Some Examples On BlueJ Week 11

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

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

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

Examples Constructing Adding Accessing ArrayList<Customer> store1 = new ArrayList<Customer> (); // newly created list, size is 0 Adding store1.add( new Customer(“William Dodds”, 349223)); // size is 1 now store1.add( new Customer(“Martha Shavers”, 255610)); // 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”, 145339); store1.set(1, newCust); // overwrites Martha with Lee Week 11

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

Adding Before add(i,a) Week 11

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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