24
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with linear or binary search

Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Embed Size (px)

Citation preview

Page 1: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Arrays

The concept of arraysUsing arraysArrays as argumentsProcessing an arrays dataMultidimensional arraysSorting data in an arraySearching with linear or binary search

Page 2: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Why arrays

Consider a program to find the average of a set of numbers.How could we do this.We could read each number one at a time Sum all of the values together and keep a count to compute the averageHow do we then find the median value. The actual value closes to the average?

Page 3: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Consider a list of 3 numbers.

Number1=5Number2=10Number3=7Which is the median. How did we find that value?What would the code look like?

Page 4: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

The median

sum = n1+n2+n3ave=sum/3If (Math.abs(ave-n1) < Math.abs(ave-

n2) && Math.abs(ave-n1) < Math.abs(ave-n3) )

median = n1Else …

Page 5: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Complex for three number even more complex for more

Arrays to the rescue.Arrays can store a list of values under the same name.Each value can be access individually using a subscript or index value or variable.

Page 6: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Array storage

The array named Data stores 5 values.Each element in a array can be used in out program just like an other variable of that type.Data[0]=5;Sum=Data[0]+Data[1]

Data[0]

5

Data[1]

10

Data[2]

7

Data[3]

2

Data[4]

13

Page 7: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Making an array

Declaring an array int[] Data; int Data[];

Allocating space for an arrays elements Arrays are reference type variable in Java so space must

be allocated for them int[] Data =new int[100]; Or ---- int[] Data; Data =new int[100];

The new key word is required when making space for reference type data

Page 8: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Properties of arrays

Indexing begins at zeroThe .length property returns the number of elements in the array.So Data.length would be 100

It is an error to access a data element in a array that is not defined. This will result in a logic error that can be difficult to debug.

Page 9: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Processing an array

A loop is used to process an array Display value Sum values Initialize values Load values

For (int x=0;x< Data.length;x++) Data[x]=0;

Page 10: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Processing arrays

When working with arrays it is common practice to create a variable to keep track of the actual valid data items in the array.Arrays may be declared at an arbitrarily large side the actual count of valid data elements in the array may be less.If this is the case then using the arrays length property is not valid.

For (int x=0;x< Data_cnt;x++) System.out.println(Data[x]);

Page 11: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Initialization lists

String[] Month ={“”,”Jan”,”Feb”,…”Dec” };System.out.println(Month[3]);int[] Data={ 5,10,7,12,2 };Can only be done when the array is declared or allocated

So this can be done later in the programData = new int[] { 5,2,5,3,1 };

Page 12: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Lets make an example

Write a program to collect grade scores from the user and store into an array.Write a loop to total the scoresWrite a loop to find the largest valueWrite a loop to count the number of time the largest value is entered.

Page 13: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Sampleimport javax.swing.*;

public class grades {

public static void main (String arg[]) { String snum; int num1=0; int i,sum; int largest; int largest_cnt;

int[] data = new int[100]; int data_cnt=0;

// read in the numbers

while (( num1>=0 ) && (data_cnt<100)) { snum = JOptionPane.showInputDialog("Enter a Number?"); num1=Integer.parseInt(snum); data[data_cnt] = num1; data_cnt++; } data_cnt--;

// print the list for(i=0; i<data_cnt;i++) { System.out.print(" " + data[i] + " "); }

sum=0; // compute the total for(i=0; i<data_cnt;i++) sum=sum+data[i];

JOptionPane.showMessageDialog(null,"The sum is"+sum,"Results", JOptionPane.PLAIN_MESSAGE);

sum=0; // compute the total for(i=0; i<data_cnt;i++) sum=sum+data[i];

JOptionPane.showMessageDialog(null,"The sum is"+sum,"Results", JOptionPane.PLAIN_MESSAGE);

largest = 0; // find the largest value for(i=0; i<data_cnt;i++) { if (data[i] > largest) largest = data[i]; } JOptionPane.showMessageDialog(null,"The largest is"+largest,"Results",

JOptionPane.PLAIN_MESSAGE);

largest_cnt=0; // Count the number of times the largest value appears in the list for(i=0; i<data_cnt;i++) { if (data[i] == largest) largest_cnt ++; } JOptionPane.showMessageDialog(null,"The count of largest is"+largest_cnt,"Results",

JOptionPane.PLAIN_MESSAGE);

System.exit(0);

} }

Page 14: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Using arrays in an assignment

newlist = listThis assignment would seem like it should copy the values from list to newlist.It does not. Remember that an array is a reference type data. So this actually causes newlist and list to reference that same data.

List elementslist

newlist

Page 15: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

To copy the data in an array

We must create a loopThen in the loop we must copy each element from one array to the destination.

List elementslist

newlistList

elements

Page 16: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Passing arrays as arguments

Arrays are passed by reference to a method.So changes to the arrays elements in the method are shared by the calling method.

Page 17: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Multidimensional arrays

Arrays can have more then one index.These are called multidimensional.So Int[][] data;Or Int data[][];Declare a two-dimensional arrayGrid = new int[5][5]; will define the memory for the array 5 by 5 in size

Page 18: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Searching an array

A form of array processingLinear search or sequential search Check each element looking for the data until

it is found. Very simple algorithm.

Binary search Only works for ordered lists. Divide and

conquer. Check the middle of the list is it high or low.

Then divide the search range in half and continue this process.

Much faster then a sequential search

Page 19: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Sorting arrays

Given an array of data order the data in some way.Maybe ascending or descending order.Maybe numeric or Alphabetic orderThe most basic form or sorting involved nested loops with comparisons and swamps

Page 20: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

So a simple exchange sort

Element

Init Pass1 Pass2 Pass3 Pass 4

Data[0] 5 2 2 2 2

Data[1] 2 5 4 4 4

Data[2] 10 10 10 5 5

Data[3] 4 4 5 10 8

Data[4] 8 8 8 8 10

Page 21: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

The code

for(out=0; o<datasize;out++){ for(in=out; in<datasize;in++) { If (data[out]<data[in]) { // swap data[out] and data[in] temp=data[out]; data[out]=data[in]; data[in]=temp; } }}

Page 22: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Let look at the same code

It is actually a little different then the process we described.It does work it is not optimalWhat could be different???

Page 23: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

An intuitive sort algorithm

Try to find the lowest value in a list then swap it with the value in the first array slot.Then find the next lowest value in the list and try to swap it with the second array slot.Continue this process for each array slot up to the end of the list.

Page 24: Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with

Homework

TBD