Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Similar presentations


Presentation on theme: "1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method."— Presentation transcript:

1 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method. – Modifying a value in a method does not have any effect on the caller – But if the value is a reference then the change affects ‘what is referred to’ and so all references will see the change. References are addresses and hence a modification of the contents at the address will have “global” visibility On the other hand non-referential argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents only of local memory)

2 2

3 3

4 The Sorting Problem Let S be a sequence of entities which can be ordered (that is for any 2 elements, say a, b in the sequence exactly one of the following is true a b or a=b). Sort(S) : arranges the sequence in ascending or descending order.

5 Sort algorithms The sorting problem is one of the best studied problems and many algorithms exist. It is also practically important – sorting is routinely required in almost all database centred applications.

6 Selection sort: example //green is min, | is separator // after first round, blue sorted //stop since only one left

7 Selection sort algorithm //S is the array to be sorted. sepIndex=0; loop (s.length-1) times { minI=findMinIndex(S,sepIndex); exchange(S,sepIndex,minI); sepIndex++; }

8 Selection sort - findMinIndex int findMinIndex(int[]S,int from) { int minI=from; for(int i=from+1;index<S.length;i++) { if (S[i]<S[minI]) minI=i; } return minI; }

9 Bubble sort: example //sort ascending, | is unsorted-sorted separator //interchange neighbours from 0 till end //after first pass //after second pass //after third pass //4th pass, no interchange Stop condition: no interchange or | is at start.

10 Bubble sort algorithm lim=S.length-1; while (bubblePass(S,lim) && lim>0) { lim--; }

11 Bubble sort - bubblePass boolean bubblePass(int [] s, int to) {boolean interchange=false; for(int i=0; i<to; i++) { if (S[i]>S[i+1]){ //exchange contents of S[i],S[i+1] interchange=true; } return interchange; }

12 Mergesort msort(s) { /* Split S into two (almost) equal parts s1,s2*/ split(s,s1,s2); msort(s1); msort(s2); /* at this point s1, s2 are sorted */ merge(s1,s2,ss); return ss; }

13 Merge merge(s1, s2, s) { s=initialize to s1.length+s2.length i1=0;i2=0,i=0; while(i1<s1.length && i2<s2.length){ if(s1[i1]<s2[i2])s[i]=s1[i1++]; else s[i]=s2[i2++]; i++ } // Now copy rest of s1 or s2 to s return s;}

14 14 Finding average class Average { public static void main (String arg[]) { double dailyRainFall[] = {12.3, 13.5, 4.2, 2.4, 1.1, 0, 10.8}; int i; double average = 0; for (i=0; i<7; i++) { average += dailyRainFall[i]; } average /= 7; System.out.println (“Average rain fall: ” + average + “ mm”); }

15 15 Finding maximum class Maximum { public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; Initialize (numbers, n); System.out.println (“Maximum: ” + FindMax (numbers, n)); }

16 16 Finding maximum public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

17 Finding maximum public static double FindMax (double numbers[], int length) { double max = numbers[0]; int i; for (i=1; i<length; i++) { if (numbers[i] > max) { max = numbers[i]; } return max; } } // end class

18 Finding maximum Want to print the position of the maximum also –Need to return two values from FindMax –Use a 2-element array as return type –Shows why returning local reference does not work –Shows the distinction between two different memory areas: stack and heap

19 Finding max and max index class Maximum { public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[]; Initialize (numbers, n); result = FindMax (numbers, n); // Danger! System.out.println ("Maximum: " + result[0] + ", Position: " + (int)result[1]); }

20 Finding max and max index public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

21 Finding max and max index public static double[] FindMax (double numbers[], int length) { // Does not work double result[] = {numbers[0], 0}; int i; for (i=1; i<length; i++) { if (numbers[i] > result[0]) { result[0] = numbers[i]; result[1] = i; } return result; // Local reference on stack } } // end class

22 Finding max and max index public static double[] FindMax (double numbers[], int length) { // This one works double result[] = new double[2]; // On heap result[0] = numbers[0]; result[1] = 0; int i; for (i=1; i<length; i++) { if (numbers[i] > result[0]) { result[0] = numbers[i]; result[1] = i; } return result; // Reference on heap } } // end class

23 Array layout in memory Recall that every variable requires some space to be stored in memory –Often the compiler is responsible for allocating this space –In other words, every variable has an address (just like you and I have addresses) –The address is often called a reference of a variable in Java –If I try to print the value at this address, I will get the value of the variable How is an array stored in memory?

24 Array layout in memory The array elements are stored contiguously in memory –numbers[0], numbers[1], … –Starting address is numbers (same as the address of numbers[0]), add 8 to get the address of numbers[1] –doubles are 64 bits in size and memory is always byte addressed (one byte is 8 bits) –Putting array names in method arguments is equivalent to passing the arrays by reference: modifications to arrays inside the method are reflected outside the method –Of course, it is possible to pass individual array elements (not by reference, but by value i.e. as private copies)

25 FindMax: reference as a value class Maximum { // Still pass by value public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[] = new double[2]; Initialize (numbers, n); result[0] = numbers[0]; result[1] = 0; FindMax (numbers, n, result); // reference System.out.println ("Maximum: " + result[0] + ", Position: " + (int)result[1]); }

26 FindMax: reference as a value public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

27 FindMax: reference as a value public static void FindMax (double numbers[], int length, double r[]) { int i; for (i=1; i<length; i++) { if (numbers[i] > r[0]) { r[0] = numbers[i]; r[1] = i; } } // end class

28 FindMax: passing values class Maximum { // This example does not work public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[] = new double[2]; Initialize (numbers, n); result[0] = numbers[0]; result[1] = 0; FindMax (numbers, n, result[0], result[1]); System.out.println ("Maximum: " + result[0] + ", Position: " + (int)result[1]); }

29 FindMax: passing values public static void Initialize (double numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) + Math.cos(2*Math.PI/(i+2)); }

30 FindMax: passing values public static void FindMax (double numbers[], int length, double max, double position) { int i; for (i=1; i<length; i++) { if (numbers[i] > max) { max = numbers[i]; position = i; } } // end class

31 Always pass by value Java always passes arguments by value –References are just a special kind of values –Modifying a value in a method does not have any effect on the caller –Modifying a value pointed to by a reference in a method does change the value in the caller also References are addresses and hence a modification of the contents at the address will have “global” visibility On the other hand, argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents of local memory)

32 Reversing an array class Reverse { public static void main (String arg[]) { int size = 10; int somethingStrange[] = new int[size]; Initialize (somethingStrange, size); PrintArray (somethingStrange, size); Reverse (somethingStrange, size); PrintArray (somethingStrange, size); }

33 Reversing an array public static void Initialize (int array[], int size) { int i; array[0] = 1; for (i=1; i<size; i++) { array[i] = (array[i-1]*3) % 23; }

34 Reversing an array public static void Reverse (int array[], int size) { int head = 0, tail = size-1; while (head < tail) { Swap (array, head, tail); head++; tail--; }


Download ppt "1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method."

Similar presentations


Ads by Google