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.

Slides:



Advertisements
Similar presentations
Intro Programming By Trevor Decker Team 1743 By Trevor Decker Team 1743.
Advertisements

Arrays part 2 Applications & such. Returning an array from a method A method can return an array, just like it can return any other kind of variable;
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Sorting1 Sorting Order in the court!. sorting2 Importance of sorting Sorting a list of values is a fundamental task of computers - this task is one of.
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,
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.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
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
Lecture 5 of Computer Science II Arrays Instructor: Mr.Ahmed Al Astal.
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.
Warm-Up: April 21 Write a loop (type of your choosing) that prints every 3 rd number between 10 and 50.
Java Unit 9: Arrays Declaring and Processing Arrays.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
COMP102 Lab 131 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
1 Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
The University of Texas – Pan American
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
Chapter 7 Arrays and Vectors Introducing Arrays Introducing Arrays Declaring Arrays, Creating Arrays, and Initializing Arrays Declaring Arrays, Creating.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 8 Arrays and Strings
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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.
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.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Working with arrays (we will use an array of double as example)
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
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.
CSI 3125, Preliminaries, page 1 Compiling the Program.
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.
The median again The steps of our algorithm: Read the size of the list, N. Declare and instantiate an array of integers, "list". Read the elements of list.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
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];
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Methods. Creating your own methods Java allows you to create custom methods inside its main body. public class Test { // insert your own methods right.
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
Chapter 7 User-Defined Methods.
Single Dimensional Arrays
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays.
Chapter 7 Single-Dimensional Arrays
Chapter 6 Arrays.
Chapter 6 Arrays Solution Opening Problem
Chapter 5 Arrays Introducing Arrays
Group Status Project Status.
25 Searching and Sorting Many slides modified by Prof. L. Lilien (even many without an explicit message indicating an update). Slides added or modified.
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.
Chapter 6 Arrays.
Chapter 6 Arrays.
Sorting.
Presentation transcript:

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 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: Liang // ‘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 }

Complexity of Selection Sort? The complexity of an algorithm provides a measure of how execution time will scale as the size of the data grows Linear Search was O(n).....if the data size doubles, the time to do Linear Search also doubles Selection Sort is O(n 2 ).....if the data size doubles, the time to do Selection Sort increases by a factor of 4. This is an expensive algorithm.....but it may be worthwhile (when?)

O(n 2 ) n n

Where do we put our arrays (and other variables)? We can declare variables (like array variables) in three different places in a program: In the main method public class Fintan{ } … public static void main(String[] args){ } … String[] nameList = new String[6]; A variable declared in the main method is only visible within that method. To use nameList in another method, you have to “pass” it to that method.

Variables in methods We can also declare variables (like array variables) in other methods: public class Fintan{ } … public static int myMethod(){ } … String[] nameList = new String[6]; A variable declared in the myMethod method is only visible within that method. The nameList variable cannot be used in the main method. public static void main(String[] args){ // nameList is not visible here: // nameList[0] = “fintan” will not work }

“Class-level” variables We do not have to always declare variables within a method. We can also declare variables as just within the class itself: public class Fintan{ } public static int myMethod(){ } … public static String[] nameList = new String[6]; The nameList variable is declared as part of the class Fintan. It is visible within the main method, the myMethod method, and any other methods. Since nameList is public it is also visible outside the class as Fintan.nameList and could be used by other programs. As with two above methods, nameList is declared static (which means there is only one nameList variable in this class). public static void main(String[] args){ }

Where to put variables? Whether you put variables within main, within methods, or at class level, is a question of style and cleanness in your programs. Put variables at the class level if they’re important to and used by the whole class. Put variables in methods if they’re only going to be used by that method (and don’t need to be accessed outside the method). Put variables in the main method if you’re going to pass them into other methods.

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.

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(); }

Example 5.7: adding and multiplying matrices Study Liang Example 5.7, pp 183 Method addMatrix uses 2 nested for-loops Method multiplyMatrix uses 3 nested for- loops! Higher dimensional matrices are possible: int[][][] arr3d = new int[5][5][5]; Use these at your own risk!!!!!

Reminder: adding matrices [[ [ [[[ ab cd y x + w a+w = z b+x d+z c+y And multiplication......