CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
CS102--Object Oriented Programming
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays Chapter 6 Chapter 6.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Selection Sort -Reading p Reading p
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
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.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
CS102--Object Oriented Programming Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
Sorting Arrays. Selection Sort  One of the easiest ways to sort the elements of an array is by using the selection sort algorithm.  Assume that the.
CS102--Object Oriented Programming Lecture 10: – Abstract Classes Copyright © 2008 Xiaoyan Li.
Intro to CS – Honors I Basic Sorting GEORGIOS PORTOKALIDIS
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Lecture 18/19 Arrays COMP1681 / SE15 Introduction to Programming.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
CMSC 202 Java Primer. July 24, 2007 Copyright © 2008 Pearson Addison-Wesley 2 A Sample Java Application.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Chapter 13 Interfaces and Inner Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Comp 248 Introduction to Programming Chapter 6 Arrays Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Lecture 5 array declaration and instantiation array reference
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Computer Programming BCT 1113
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Arrays 2/4 By Pius Nyaanga.
Chapter 6 Arrays Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Searching and Sorting Linear Search Binary Search ; Reading p
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Suggested self-checks: Section 7.11 #1-11
CSS161: Fundamentals of Computing
Classes, Objects and Methods
Programming with Arrays 2
Arrays 3/4 June 3, 2019 ICS102: The course.
Chapter 6 Arrays.
Arrays.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li

Exercise 1: Write a program that reads in a line of text and then first output the total number of words/tokens (separated by whitespace characters) in that line of text and then individual words one at a line. The classes you may want to use – The Scanner class in java.util package Scanner keyboard = new Scanner(System.in); public String nextLine(); – The String class in java.lang – The StringTokenizer class pubic StringTokenizer(String theString); pubic StringTokenizer(String theString, String delimiters); public int countTokens(); public String nextToken(); public boolean hasMoreTokens();

Exercise 2: Write a program that reads 2 integers and then output the numbers from the smallest to the largest. Exercise 3: Write a program that reads 3 integers and then output the numbers from the smallest to the largest. Exercise 4: Write a program that reads 10 integers and then output the numbers from the smallest to the largest.

Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type – An array behaves like a numbered list of variables with a uniform naming mechanism – For example, Give four numbers: number[0], number[1], number[3], number[4] given five scores: score[0], score[1], score[2], score[3], score[4] 6-4 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Creating and Accessing Arrays An array that behaves like this collection of variables, all of type double, can be created using one statement as follows: double[] score = new double[5]; Or using two statements: double[] score; score = new double[5]; – The first statement declares the variable score to be of the array type double[] – The second statement creates an array with five numbered variables of type double and makes the variable score a name for the array 6-5 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Creating and Accessing Arrays The individual variables that together make up the array are called indexed variables – They can also be called subscripted variables or elements of the array – The number in square brackets is called an index or subscript – In Java, indices must be numbered starting with 0, and nothing else score[0], score[1], score[2], score[3], score[4] 6-6 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Creating and Accessing Arrays double[] score = new double[5]; A variable may be used in place of the integer (i.e., in place of the integer 5 above ) – The value of this variable can then be read from the keyboard – This enables the size of the array to be determined when the program is run double[] score = new double[count]; An array can have indexed variables of any type, including any class type All of the indexed variables in a single array must be of the same type, called the base type of the array 6-7 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Referring to Arrays and Array Elements An element in the array – score[0] – An index can also be a variable or an expression. score[index] Score[next+1] The array itself: – score 6-8 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Using the score Array in a Program The for loop is ideally suited for performing array manipulations: for (index = 0; index < 5; index++) System.out.println(score[index]); 6-9 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Three Ways to Use Square Brackets [] with an Array Name Declare an array variable: double[] score; create a new array with 5 elements/indexed variables: score = new double[5]; Access an array element: max = score[0]; 6-10 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The length Instance Variable An array is considered to be an object in java Since other objects can have instance variables, so can arrays Every array has exactly one instance variable named length – When an array is created, the instance variable length is automatically set equal to its size – The value of length cannot be changed (other than by creating an entirely new array with new ) double[] score = new double[5]; – Given score above, score.length has a value of Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Initializing Arrays An array can be initialized when it is declared – Values for the indexed variables are enclosed in braces, and separated by commas – The array size is automatically set to the number of values in the braces int[] age = {2, 12, 1}; – Given age above, age.length has a value of Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Initializing Arrays: another way Example: – How to set an initial value of 42 to every element in an array. double[] reading = new double[100]; Another way of initializing an array is by using a for loop int index; for (index = 0; index < reading.length; index++) reading[index] = 42.0; 6-13 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arrays and References Like class types, a variable of an array type holds a reference – Arrays are objects – A variable of an array type holds the address of where the array object is stored in memory – Array types are (usually) considered to be class types 6-14 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arrays are Objects An array can be viewed as a collection of indexed variables An array can also be viewed as a single item whose value is a collection of values of a base type – An array variable names the array as a single item double[] a; – A new expression creates an array object and stores the object in memory new double[10] – An assignment statement places a reference to the memory address of an array object in the array variable a = new double[10]; 6-15 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arrays Are Objects The previous steps can be combined into one statement double[] a = new double[10]; Note that the new expression that creates an array invokes a constructor that uses a nonstandard syntax Not also that as a result of the assignment statement above, a contains a single value: a memory address or reference Since an array is a reference type, the behavior of arrays with respect to assignment ( = ), equality testing ( == ), and parameter passing are the same as that described for classes 6-16 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arrays with a Class Base Type The base type of an array can be a class type Date[] holidayList = new Date[20]; The above example creates 20 indexed variables of type Date – It does not create 20 objects of the class Date – Each of these indexed variables are automatically initialized to null – Any attempt to reference any them at this point would result in a "null pointer exception" error message 6-17 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arrays with a Class Base Type Like any other object, each of the indexed variables requires a separate invocation of a constructor using new () to create an object to reference holidayList[0] = new Date();... holidayList[19] = new Date(); OR for (int i = 0; i < holidayList.length; i++) holidayList[i] = new Date(); Each of the indexed variables can now be referenced since each holds the memory address of a Date object 6-18 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods 6-19 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Array Parameters double n = 0.0; double[] a = new double[10];//all elements //are initialized to 0.0 int i = 3; Given myMethod which takes one argument of type double, then all of the following are legal: myMethod(n);//n evaluates to 0.0 myMethod(a[3]);//a[3] evaluates to 0.0 myMethod(a[i]);//i evaluates to 3, //a[3] evaluates to Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Array Parameters An argument to a method may be an entire array Array arguments behave like objects of a class – Therefore, a method can change the values stored in the indexed variables of an array argument A method with an array parameter must specify the base type of the array only BaseType[] – It does not specify the length of the array 6-21 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Array Parameters The following method, doubleElements, specifies an array of double as its single argument: public class SampleClass { public static void doubleElements(double[] a) { int i; for (i = 0; i < a.length; i++) a[i] = a[i]*2;... }... } 6-22 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Array Parameters Arrays of double may be defined as follows: double[] a = new double[10]; double[] b = new double[30]; Given the arrays above, the method doubleElements from class SampleClass can be invoked as follows: SampleClass.doubleElements(a); SampleClass.doubleElements(b); – Note that no square brackets are used when an entire array is given as an argument – Note also that a method that specifies an array for a parameter can take an array of any length as an argument 6-23 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Methods That Return an Array In Java, a method may also return an array – The return type is specified in the same way that an array parameter is specified public static int[] incrementArray(int[] a, int increment) { int[] temp = new int[a.length]; int i; for (i = 0; i < a.length; i++) temp[i] = a[i] + increment; return temp; } 6-24 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Sorting an Array A sort method takes in an array parameter a, and rearranges the elements in a, so that after the method call is finished, the elements of a are sorted in ascending order How? 6-25 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Selection Sort (Part 1 of 2) 6-26 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Selection Sort (Part 2 of 2) 6-27 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Define your SelectionSort class public class SelectionSort { }

Define your SelectionSort class public class SelectionSort { public static void sort(double[] a, int count) { } private static int indexOfSmallest(int startIndex, double[] a, int count) { } private static void interchange(int i, int j, double[] a) { }

SelectionSort Class (Part 1 of 4) public class SelectionSort { /** Precondition: count <= a.length; The first count indexed variables have values. Action: Sorts a so that a[0] <= a[1] <=... <= a[count - 1]. */ 6-30 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

SelectionSort Class (Part 2 of 4) public static void sort(double[] a, int count) { int index, indexOfNextSmallest; for (index = 0; index < count - 1; index++) {//Place the correct value in a[index]: indexOfNextSmallest = indexOfSmallest(index, a, count); interchange(index,indexOfNextSmallest, a); } 6-31 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

SelectionSort Class (Part 3 of 4) /** Returns the index of the smallest value among a[startIndex], a[startIndex+1],... a[numberUsed - 1] */ private static int indexOfSmallest(int startIndex, double[] a, int count) { double min = a[startIndex]; int indexOfMin = startIndex; int index; for (index = startIndex + 1; index < count; index++) if (a[index] < min) { min = a[index]; indexOfMin = index; //min is smallest of a[startIndex] through //a[index] } return indexOfMin; } 6-32 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

SelectionSort Class (Part 4 of 4) /** Precondition: i and j are legal indices for the array a. Postcondition: Values of a[i] and a[j] have been interchanged. */ private static void interchange(int i, int j, double[] a) { double temp; temp = a[i]; a[i] = a[j]; a[j] = temp; //original value of a[i] } 6-33 Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Exercise 5: Write a program that reads 10 integers and then output the numbers from the smallest to the largest. Step1: Read 10 integers into an array Step2: Call the sort method in the class SelectionSort Step3: output the array

Announcement: Programming assignment 2: – Page 328: project 4. Page 409: project 6. – Due date: Monday, Feb 25. Late work may be submitted on Tuesday or Wednesday with 5% penalty per day. No work will be accepted after Wednesday. – How to turn in: your files to TA and me with “cs102 assignment2” in your message subject line. – Grading. Correctness: 80 points. Readability: 20 points. Next lecture: – Multi-dimensional arrays – The Arrays class