42
Arrays part 2 Applications & such

Arrays part 2

Embed Size (px)

DESCRIPTION

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; example: public PlayingCard [] newDeck () { PlayingCard deck = new PlayingCard[52]; for (int x=0; x

Citation preview

Page 1: Arrays part 2

Arrays part 2

Applications & such

Page 2: Arrays part 2

Returning an array from a method

• A method can return an array, just like it can return any other kind of variable; example:

public PlayingCard [] newDeck () {

PlayingCard deck = new PlayingCard[52];

for (int x=0; x<52; x++)

deck[x] = new PlayingCard();

return deck;

}

Page 3: 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

Page 4: Arrays part 2

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

Page 5: Arrays part 2

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

Page 6: Arrays part 2

Are the dice fair?

• The possible dice combinations are these (repeat combinations are not shown):

Page 7: Arrays part 2

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

Page 8: Arrays part 2

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

Page 9: Arrays part 2

Code for example 1import 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; }

Page 10: Arrays part 2

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

Page 11: Arrays part 2

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!"); }}

Page 12: Arrays part 2

Sample output from example 1Testing dice ...After rolling dice 100,000 times, we have:2: 28063: 55114: 83775: 110946: 139587: 165938: 138039: 1123010: 823011: 560312: 2795Dice are fair - we can play

Page 13: Arrays part 2

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

Page 14: Arrays part 2

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

Page 15: Arrays part 2

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 % 100 + 1; 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"); } }

Page 16: Arrays part 2

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 ...

Page 17: Arrays part 2

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

Page 18: Arrays part 2

Sorting an Array of IntegersSorting an Array of Integers

• The picture shows an array of six integers that we want to sort from smallest to largest

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6][0] [1] [2] [3] [4] [5]

Page 19: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Selectionsort AlgorithmThe Selectionsort Algorithm

• Start by finding the smallest entry.

• Swap the smallest entry with the first entry.

[0] [1] [2] [3] [4] [5]

Page 20: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Selectionsort AlgorithmThe Selectionsort Algorithm

• Part of the array is now sorted.

Sorted side Unsorted side

[0] [1] [2] [3] [4] [5]

Page 21: Arrays part 2

The Selectionsort AlgorithmThe Selectionsort Algorithm

• Find the smallest element in the unsorted side.

Sorted side Unsorted side

[0] [1] [2] [3] [4] [5]

Page 22: Arrays part 2

The Selectionsort AlgorithmThe Selectionsort Algorithm

• Swap with the front of the unsorted side.

Sorted side Unsorted side

[0] [1] [2] [3] [4] [5]

Page 23: Arrays part 2

The Selectionsort AlgorithmThe Selectionsort Algorithm

• We have increased the size of the sorted side by one element.

Sorted side Unsorted side

[0] [1] [2] [3] [4] [5]

Page 24: Arrays part 2

The Selectionsort AlgorithmThe Selectionsort Algorithm

• The process continues...

Sorted side Unsorted side

Smallestfrom

unsorted

Smallestfrom

unsorted

[0] [1] [2] [3] [4] [5]

Page 25: Arrays part 2

The Selectionsort AlgorithmThe Selectionsort Algorithm

• The process continues...

Sorted side Unsorted side

[0] [1] [2] [3] [4] [5]

Swap

with

front

Swap

with

front

Page 26: Arrays part 2

The Selectionsort AlgorithmThe Selectionsort Algorithm

• The process continues...

Sorted side Unsorted sideSorted side

is bigger

Sorted sideis bigger

[0] [1] [2] [3] [4] [5]

Page 27: Arrays part 2

The Selectionsort AlgorithmThe 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]

Page 28: Arrays part 2

The Selectionsort AlgorithmThe 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]

Page 29: Arrays part 2

The Selectionsort AlgorithmThe 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]

Page 30: Arrays part 2

Implementation of Selectionsortpublic 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; } }

Page 31: Arrays part 2

Sample outputBefore sort:

59 20 51 38 65 75 36 91 4 6535 21 89 64 34 76 12 93 48 8232 71 99 90 13 26 76 47 44 8378 77 29 81 51 21 55 79 83 217 99 63 3 92 99 48 91 40 8714 77 53 4 62 19 15 20 55 466 71 86 37 86 56 76 54 19 3688 51 38 64 16 28 50 23 22 810 51 34 80 33 16 34 17 79 1666 64 60 66 9 7 19 61 62 28

After sort:

3 4 4 4 7 7 8 9 10 1213 14 15 16 16 16 17 19 19 1920 20 21 21 21 22 23 26 28 2829 32 33 34 34 34 35 36 36 3738 38 40 44 47 48 48 50 51 5151 51 53 54 55 55 56 59 60 6162 62 63 64 64 64 65 65 66 6666 71 71 75 76 76 76 77 77 7879 79 80 81 82 83 83 86 86 8788 89 90 91 91 92 93 99 99 99

Page 32: Arrays part 2

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

Page 33: Arrays part 2

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

Page 34: Arrays part 2

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

Page 35: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe Insertionsort Algorithm

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

Page 36: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe 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

Page 37: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe 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

Page 38: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe 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

Page 39: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe 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

Page 40: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe 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

Page 41: Arrays part 2

0

10

20

30

40

50

60

70

[1] [2] [3] [4] [5] [6]

The Insertionsort AlgorithmThe Insertionsort Algorithm

• Sometimes we are lucky twice in a row.

[0] [1] [2] [3] [4] [5]

Sorted side Unsorted side

Page 42: Arrays part 2

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