Arrays, part 2. Array applications Arrays are useful whenever a relatively large amount of data must be kept available in memory for processing We will.

Slides:



Advertisements
Similar presentations
P p Two slow but simple algorithms are Selectionsort and Insertionsort. p p This presentation demonstrates how the two algorithms work. Quadratic Sorting.
Advertisements

Programming and Data Structure
Sorting I Chapter 8 Kruse and Ryba. Introduction Common problem: sort a list of values, starting from lowest to highest. –List of exam scores –Words of.
  Chapter 12 presents several common algorithms for sorting an array of integers.   Two slow but simple algorithms are Selectionsort and Insertionsort.
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
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.
A Java API Package java.security  The Java Security Package contains classes and interfaces that are required by many Java programs.  This package is.
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.
CSC212 Data Structure - Section FG Lecture 21 Quadratic Sorting Instructor: Zhigang Zhu Department of Computer Science City College of New York.
Arrays Chapter 6 Chapter 6.
8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 Arrays.
Chapter 10 Arrays. Topics Declaring and instantiating arrays Array element access Arrays of objects Arrays as method parameters Arrays as return values.
Copyright © 1999, Carnegie Mellon. All Rights Reserved. Chapter 12 presents several common algorithms for sorting an array of integers. Two slow but simple.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
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 Foundations of Software Design Fall 2002 Marti Hearst Lecture 20: Sorting.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 8 Arrays and Strings
Lecture 5 of Computer Science II Arrays Instructor: Mr.Ahmed Al Astal.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 11 Sorting Algorithms. Sorting Sorting Algorithms A sorting algorithm is an algorithm that puts elements of a list in a certain order. We need sorting.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 14: Sorting and searching. Chapter Goals To study several sorting and searching algorithms To appreciate that algorithms for the same task can.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Lists in Python.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays : Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection of data values, using an array. –Declare.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Sorting Sorting Arranging items in a collection so that there is an ordering on one (or more) of the fields in the items Sort Key The field (or fields)
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
CSC211 Data Structures Lecture 21 Quadratic Sorting Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Sort Algorithms.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
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.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
CSCI 51 Introduction to Programming March 10, 2009.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
Lecture 5 of Computer Science II
Lecture 14 Searching and Sorting Richard Gesick.
Sorting Chapter 13 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and Insertionsort.
Chapter 10 Arrays ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Quadratic Sorting Chapter 12 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and.
Lecture 11 Searching and Sorting Richard Gesick.
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.
Sorting Chapter 13 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and Insertionsort.
Sorting and Searching -- Introduction
Sorting.
Arrays.
Presentation transcript:

Arrays, part 2

Array applications Arrays are useful whenever a relatively large amount of data must be kept available in memory for processing We will look at several examples of array applications, and see how arrays can be used as arguments to methods and as method return values

Application 1: frequency counter A common programming problem involves counting the number of times particular values are found in a data set, or particular events occur while a program is running An array can be used as a frequency counter, keeping track of the frequency of occurrence of several events at a time

Example: are the dice fair? For our first example, consider the dice game craps: –The game involves rolling two six-sided dice –Both dice have a pattern of dots on each of their sides; each has a side with 1, 2, 3, 4, 5 and 6 dots –When the dice are rolled, whichever sides land up determine the score for the roll; for example, if the dice read 3 and 4, the player rolled a 7

Are the dice fair? The possible dice combinations are these (repeat combinations are not shown):

Determining fairness With fair dice, the most common roll should be 7, since there are more combinations (two each of 1-6, 2-5, and 3-4) that add up to 7 than any other combination We should see a 7 come up one-sixth of the time A Java program that plays craps would use a random number generator to simulate the roll of the dice We can use an array as a frequency counter to determine if the simulated dice are fair

Testing dice fairness First, we’ll write a method that produces a random number between 1 and 6 To test the fairness of our method, we will call it from within a loop that runs several thousand times; each time we roll (by calling the method twice, once for each die), we will record the score by incrementing an index in a frequency- counting array When the loop is finished, we’ll examine the array to see how often we rolled a 7

Code for example 1 import java.util.*; public class DiceGame { private Random rg; // generates random # to represent roll public DiceGame () { // initialize random number generator rg = new Random(); } public int rollDice () { // return a number between 1 and 6 int cube = rg.nextInt(); cube = Math.abs(cube); cube = cube % 6 + 1; return cube; }

Code for example 1 public boolean testDice () { boolean fair = false; int [] diceCounter = new int [13]; for (int x=0; x<13; x++) diceCounter[x] = 0; int die1, die2; for (int y=0; y<100000; y++) { die1=rollDice(); die2=rollDice(); diceCounter[die1+die2]++; } System.out.println ("After rolling dice 100,000 times, we have:"); for (int z=2; z<13; z++) System.out.println (z + ":\t" + diceCounter[z]); if (diceCounter[7] >= (1.0/6.0)) fair = true; return fair; }

Code for example 1 public static void main (String [] args) { DiceGame dg = new DiceGame(); System.out.println ("Testing dice..."); boolean areFair = dg.testDice(); if (areFair) System.out.println ("Dice are fair - we can play"); else System.out.println ("These dice are loaded!"); }

Sample output from example 1 Testing dice... After rolling dice 100,000 times, we have: 2:2806 3:5511 4:8377 5: : : : : : : :2795 Dice are fair - we can play

Application 2: sorting algorithms Sorting is one of the most basic operations of computers; the need to sort data was one of the motivating factors for the invention of automatic computing machines We will take a brief look at a few of the many sorting algorithms that have been developed over the years, using an array of random integers as our data set

A testbed for sorting algorithms The next slide presents some of the methods of a class that is designed to test various sorting algorithms The class contains an array of random integers and the means to copy and print this array, as well as implementations of a few well-known sorting algorithms

Sorter class – private members, default constructor, utility methods import java.util.*; public class Sorter { private int [] numbers; private Random rg; public Sorter () { numbers = new int [100]; rg = new Random(); for (int x = 0; x<100; x++) { int tmp = rg.nextInt(); tmp = Math.abs(tmp); tmp = tmp % ; numbers[x] = tmp; } public int [] copyArray () { int [] sorted = new int [numbers.length]; for (int x=0; x < numbers.length; x++) sorted[x] = numbers[x]; return sorted; } public static void printArray (int [] array) { for (int x=0; x<array.length; x++) { if (x % 10 == 0) System.out.print("\n"); System.out.print (array[x] + "\t"); }

Selectionsort Goal of the algorithm is to sort a list of values (for example, integers in an array) from smallest to largest The method employed comes directly from this statement of the problem –find smallest value and place at front of array –find next-smallest value and place in second position –find next-next-smallest and place in third position –and so on...

Selectionsort The mechanics of the algorithm are simple: swap the smallest element with whatever is in the first position, then move to the second position and perform a similar swap, etc. In the process, a sorted subarray grows from the front, while the remaining unsorted subarray shrinks toward the back

Sorting an Array of Integers The picture shows an array of six integers that we want to sort from smallest to largest [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm Start by finding the smallest entry. Swap the smallest entry with the first entry. [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm Part of the array is now sorted. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm Find the smallest element in the unsorted side. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm Swap with the front of the unsorted side. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm We have increased the size of the sorted side by one element. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm The process continues... Sorted side Unsorted side Smallest from unsorted Smallest from unsorted [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm The process continues... Sorted side Unsorted side [0] [1] [2] [3] [4] [5] Swap with front Swap with front

The Selectionsort Algorithm The process continues... Sorted side Unsorted side Sorted side is bigger Sorted side is bigger [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm The process keeps adding one more number to the sorted side. The sorted side has the smallest numbers, arranged from small to large. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm We can stop when the unsorted side has just one number, since that number must be the largest number. [0] [1] [2] [3] [4] [5]

The Selectionsort Algorithm The array is now sorted. We repeatedly selected the smallest element, and moved this element to the front of the unsorted side. [0] [1] [2] [3] [4] [5]

Implementation of Selectionsort public void selectionSort () { int mindex, len, tmp; len = numbers.length; for (int x = 0; x <= len-2; x++) { mindex = x; for (int y = x+1; y <= len-1; y++) if (numbers[y] < numbers[mindex]) mindex = y; tmp = numbers[x]; numbers[x] = numbers[mindex]; numbers[mindex] = tmp; }

Sample output Before sort: After sort:

Insertionsort Although based on the same principle as Selectionsort (sorting a portion of the array, adding one element at a time to the sorted portion), Insertionsort takes a slightly different approach Instead of selecting the smallest element from the unsorted side, Insertionsort simply takes the first element and inserts it in place on the sorted side so that the sorted side is always in order

Insertionsort algorithm Designate first element as sorted Take first element from unsorted side and insert in correct location on sorted side: –copy new element –shift elements from end of sorted side to the right (as necessary) to make space for new element

Insertionsort algorithm Correct location for new element found when: –front of array is reached or –next element to shift is <= new element Continue process until last element has been put into place

The Insertionsort Algorithm The Insertionsort algorithm also views the array as having a sorted side and an unsorted side. [0] [1] [2] [3] [4] [5]

The Insertionsort Algorithm The sorted side starts with just the first element, which is not necessarily the smallest element. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertionsort Algorithm The sorted side grows by taking the front element from the unsorted side... [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertionsort Algorithm...and inserting it in the place that keeps the sorted side arranged from small to large. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertionsort Algorithm In this example, the new element goes in front of the element that was already in the sorted side. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertionsort Algorithm Sometimes we are lucky and the new inserted item doesn't need to move at all. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertionsort Algorithm Sometimes we are lucky twice in a row. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

Implementation of Insertionsort public void insertionSort () { int x, y, tmp; for (x=1; x<numbers.length; x++) { tmp = numbers[x]; for (y=x; y>0 && numbers[y-1] > tmp; y--) numbers[y] = numbers[y-1]; numbers[y] = tmp; }

Passing Arrays to Methods Arrays and objects are reference data types, so the rules for passing an object to a method and returning an object from a method apply to arrays. Consider an example method that returns the index of the smallest element in an array of real numbers

Passing Arrays to Methods public int searchMinimum(double[] number) { int indexOfMinimum = 0; for (int i = 1; i < number.length; i++){ if (number[i] < number[indexOfMinimum]) { //found a smaller element indexOfMinimum = i; } return indexOfMinimum; }

Passing Arrays to Methods double[] arrayOne; //create and assign values to arrayOne... //get the index of the smallest element of arrayOne int minOne = searchMinimum(arrayOne); //output the result System.out.print(“Minimum value in Array One is ”); System.out.print(arrayOne[minOne] + “at position ” + minOne);...

Passing Arrays to Methods Remember that when an array is passed to a method, only its reference is passed. A copy of the array is not created in the method.

Passing Arrays to Methods Next we will consider an example in which we return an array from a method. This method inputs double values and returns the values as an array of double.

Passing Arrays to Methods public double[] readDoubles() { double[] number; int N = Integer.ParseInt( JOptionPane.showInputDialog(null, “How many input values?”)); number = new double[N]; for (int i = 0; i<N; i++){ number[i] = Double.parseDouble( JOptionPane.showInputDialog(null, “Number ” + i)); } return number; }

Passing Arrays to Methods The readDoubles method is called: double[] arrayOne; //assign values to arrayOne arrayOne = readDoubles(); Because a new array is created by the method, we do not have to create an array from the calling side. Doing so will not cause an error, but it is a wasteful operation.

The effect of creating a local array and not returning it

Two-Dimensional Arrays In Java, data may be organized in a two- dimensional array. A table is an example of a two-dimensional array. In a two-dimensional array, two indices (in a table, one for the row and one for the column) are used to refer to the array element.

Two-Dimensional Arrays To declare our example array, we state: double[][] payScaleTable; or double payScaleTable[][]; and create the array as payScaleTable = new double[4][5];

Examples of information represented as tables.

Two-Dimensional Arrays To refer to an element at the second column (column 1) of the third row (row 2), we say payScaleTable[2][1] Nested-for loops are useful for manipulating two-dimensional arrays.

Accessing an element of a two- dimensional array

Two-Dimensional Arrays The concept of the two-dimensional array in Java is just that: a concept. There is no explicit structure called the “two- dimensional array” in Java. The two-dimensional array concept is implemented by using an array of arrays.

Two-Dimensional Arrays The sample array creation payScaleTable = new double[4][5]; is a shorthand for payScaleTable = new double [4][ ]; payScaleTable[0] = new double [5]; payScaleTable[1] = new double [5]; payScaleTable[2] = new double [5]; and so on.

Statements on the left in sequence create array of arrays on the right

Continued from previous slide

Two-Dimensional Arrays The expression payScaleTable.length refers to the length of the array itself.

Two-Dimensional Arrays The expression payScaleTable[1].length refers to the length of the array stored at row 1 of payScaleTable.

Two-Dimensional Arrays An array that is part of another array is called a subarray. An array of arrays may be initialized when it is created.

Two-Dimensional Arrays Subarrays may be different lengths. Executing this code: triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like: