Post on 02-Jan-2016
Arrays
The concept of arraysUsing arraysArrays as argumentsProcessing an arrays dataMultidimensional arraysSorting data in an arraySearching with linear or binary search
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?
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?
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 …
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.
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
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
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.
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;
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]);
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 };
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.
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);
} }
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
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
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.
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
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
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
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
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; } }}
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???
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.
Homework
TBD