Horstmann chapter 8 continued. Sorting arrays The telephone book is easy to use, because the entries are sorted Sorting is a common task, and many many.

Slides:



Advertisements
Similar presentations
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
Liang, Chpt 5 continued. Sorting arrays The telephone book is easy to use, because the entries are sorted Sorting is a common task, and many many algorithms.
Arrays Liang, Chpt 5. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
Array Must declare a variable to reference the array double [] mylist; // cannot double list[20]; Or double mylist[]; The declaration doesn’t allocate.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Chapter 8 Arrays and Strings
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.
Java Unit 9: Arrays Declaring and Processing Arrays.
Lists in Python.
The University of Texas – Pan American
1 Chapter 7 Single-Dimensional Arrays. 2 Arrays Array is a data structure that represents a collection of the same types of data elements. A single-dimensional.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 8 Arrays and Strings
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Liang, Introduction to Java Programming1 Arrays Gang Qian Department of Computer Science University of Central Oklahoma.
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.
Working with arrays (we will use an array of double as example)
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
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.
Arrays. Collections We would like to be able to keep lots of information at once Example: Keep all the students in the class Grade each one without writing.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 6 Arrays.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Chapter 6 Arrays 1 Fall 2012 CS2302: Programming Principles.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 6 Arrays 1.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Copyright Prentice Hall Modified by Sana odeh, NYU
Single Dimensional Arrays
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays.
Arrays An Array is an ordered collection of variables
Chapter 6 Arrays Solution Opening Problem
Chapter 5 Arrays Introducing Arrays
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays.
Object Oriented Programming
Chapter 6 Arrays.
Chapter 23 Searching and Sorting
Chapter 7 Single-Dimensional Arrays
Presentation transcript:

Horstmann chapter 8 continued

Sorting arrays The telephone book is easy to use, because the entries are sorted Sorting is a common task, and many many algorithms are available An array need only be sorted once, and can then be searched many times We will use one specific algorithm: Selection Sort

Selection Sort Initially, the whole array is unsorted Until the array is sorted, do the following: Find the largest element in the unsorted array If it is not the final element in the unsorted portion of the array, swap it with the final element of the unsorted portion Reduce the unsorted portion by one (from the right)

Selection Sort illustrated // the whole list is unsorted (els 0..6) // the largest element is non-final // swap them. Elements 0..5 are now unsorted // 8 is largest and non-final // 6 is largest and non-final // 5 is largest and non-final // 4 is largest, and final: do nothing // 2 is largest and non-final // finished once the unsorted bit is less tha 2 el.s In this example, the underlined section of the array is the unsorted part of that array, and the non-underlined section is the part that is correctly sorted.

Anatomy of the SelectionSort program public class SelectionSort { public static void main(String[] args){ // make a list, print it, sort it, print it again } public static void printList(double[] list) { } public static void selectionSort(double[] list) { } }

Implementing Selection Sort // ‘i’ holds the index of the end of the // unsorted section of the list. This goes // down by one each time we do a selection for(int i=list.length-1; i>0; i--) { // find max in list[0]..list[i] // swap max with list[i] if necessary }

Passing arrays in to methods public static int max(int num1, int num2) modifiers return type method name parameters each parameter has a type and a name. This tells us that method max is public, takes two integers as arguments (in the method these are called num1 and num2 ), and returns an integer as its answer. public static int max(int[] mylist) modifiers return type method name parameter This method takes an array as its argument This tells us that method max is public, takes an array of integers as its argument (within the method this will be called mylist ), and returns an integer as its answer. We can also give arrays as arguments:

An array argument in the main method public static void main(String[] args) { This line tells us that main is a method which takes an array of Strings as its argument, and calls that array args public class Fintan { … What does this mean? It means that when we run our program from the command line, we can give extra arguments that go in the args array: >javac Fintan.java >java Fintan first second third Now first second and third are arguments to the main method of the Fintan program: args[0]=“first”, args[1]=“second”, rgs[2]=“third”. These args can be used in the program.

Generalised for Loop (a ‘for each’ loop) A “for each” loop for all elements of a collection: double[] data =...; double sum = 0; for (double e : data) // read this as "for each e in data" { sum = sum + e; } Standard for loop doing the same thing for (int i = 0; i < data.length; i++) { double e = data[i]; sum = sum + e; }

Syntax 8.3: The "for each" Loop for (Type variable-name : collection) statement Example: for (double e : data) sum = sum + e; Purpose: To execute a loop for each element in the collection. In each iteration, the variable is assigned the next element of the collection. Then the statement is executed.

Different forms of “for” loop. Arrays and for-loops are closely connected. Why? Because you use a for-loop to go through the elements in an array. When writing a program, there is a noticeable difference between what you can do with a for (double e: data) loop and a for (int x=0; x <data.length;x++) loop. What is the difference? In the “for each” loop, you don’t know the number of the current element. In the standard for loop, that number is in the variable being used.

Copying Arrays Why does this run into problems? int[] list1 = {0, 1, 2, 3, 4, 5}; int[] list2 = new int[list1.length]; list2 = list1; list1[0] = 99; System.out.println(list2[0]);

What's happening? list list

What's happening? list list For a more complete example: Liang, Example 5.6, pp 177ff

Three possible solutions 1.Element-by-element copy 2.Create a clone of the array (later) 3.Use System.arrayCopy() -- a static method

Element-by-element copy int[] source = {0,1,2,3,4,5}; int[] target = new int[source.length]; for(int i=0; i<source.length; i++) { target[i] = source[i]; }

Using System.arrayCopy System.arrayCopy(source, 0, target, 0, sourceArray.length); source array starting position.....(source) target array starting position (target) How many elements should be copied?

Multidimensional Arrays This array is one-dimensional: int[] list1 = {4, 2, 6, 3, 8, 4, 9, 5}; This array is 2-D (a matrix): int[][] matrix1 = { {1, 2, 3, 4}, {2, 4, 6, 8}, {3, 6, 9, 12} };

Creating a 5*5 matrix of random values double[][] ranMatrix = new double[5][5]; for(int i=0; i<5; i++) { for(int j=0; j<5; j++) { ranMatrix[i][j] = Math.random(); }