Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with."— Presentation transcript:

1 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

2 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 average How do we then find the median value. The actual value closes to the average?

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

4 The median sum = n1+n2+n3 ave=sum/3 If (Math.abs(ave-n1) < Math.abs(ave-n2) && Math.abs(ave-n1) < Math.abs(ave- n3) ) median = n1 Else …

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

6 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

7 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

8 Properties of arrays Indexing begins at zero The.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.

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

10 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]);

11 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 program Data = new int[] { 5,2,5,3,1 };

12 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 scores Write a loop to find the largest value Write a loop to count the number of time the largest value is entered.

13 Sample import 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); }

14 Using arrays in an assignment newlist = list This 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 elements list newlist

15 To copy the data in an array We must create a loop Then in the loop we must copy each element from one array to the destination. List elements list newlist List elements

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

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

18 Searching an array A form of array processing Linear 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

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

20 So a simple exchange sort ElementInitPass1Pass2Pass3Pass 4 Data[0]52222 Data[1]25444 Data[2]10 55 Data[3]445108 Data[4]888810

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

22 Let look at the same code It is actually a little different then the process we described. It does work it is not optimal What could be different???

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

24 Homework TBD


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

Similar presentations


Ads by Google