Arrays and Methods

"They have computers, and they may have other weapons of mass destruction."
-- Janet Reno

As with other reference types, arrays can be:
• passed as arguments to a method
• returned from a method

Arrays as Arguments

• Arrays can be used as arguments to methods like any other type.
• Since arrays are references, the method can actually change the array's elements.

Example
:
public class changeArray
{
public static void oops(int[] a)
{
int n = a.length; // notice that this is NOT a method call!
int zero = a[0];
a[0] = a[n-1];
a[n-1] = zero;
} // what does this method do??

public static void main(String[] args)
{
int[] myArray = {1, 2, 3, 4};
oops(myArray);
for(int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
}
}

Output:
4
2
3
1

Exercise:
Write a program that contains a method that takes an array of doubles, and returns the sum of the array's elements. Test this method in your program's main method.

Exercise: Write a method that takes as its arguments an array of integers, and an integer value, and returns the index of the first occurrence of that integer value in the array. If the integer does not occur in the array, return -1.

Exercise: Write a swap() method that takes an array of integers, and two integer indexes i and j, and swaps the position of the array entries at index i and j. If one or both indices (i and j) are invalid, the method should do nothing.

Exercise: Write a program that reads 10 integers from the keyboard and stores them in an array. Write a method called reverse that reverses the order of the elements in the array. In the main method, print the array, call reverse, and then print the array again.

Arrays as Return Values

• When you want to return a sequence of values from a method, use an array as the return type.

Example:

public class genArray
{
public static int[ ] fillArray(int size)
{
// Creates array containing integers 1 to size
int[ ] result = new int[size];

for(int i = 0; i < size; i++)
{
result[i] = i+1;
}
return result;
}

public static void main(String[] args)
{
int[ ] a = fillArray(5);
for(int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}

Output:
1
2
3
4
5

Exercise: Write a program that includes a method that takes 2 integers and creates and returns an array that contains all the integer values between them. That is, if the integers passed to the method are -1 and 7, the method should return an array that contains -1, 0, 1, 2, 3, 4, 5, 6, 7. In your main method, call this method to create several arrays and then print them.

Useful Methods for Arrays

java.lang.System methods

static void arraycopy(Object from, int fromIndex, Object to, int toIndex, int count)

java.util.Arrays methods

static void sort(Type[ ] a)
sorts an array of type int, long, short, char, byte, boolean, float or double into ascending order

static int binarySearch(Type[ ] a, Type v)
a is a sorted array of type int, long, short, char, byte, boolean, float or double.
The binary search algorithm is used to search for value v. If v is in a, then v's index is returned; otherwise a negative value is returned.

static boolean equals(Type[ ] a, Object other)
a is an array of type int, long, short, char, byte, boolean, float or double.
This method returns true if other is an array of the same type and size, and the elements in corresponding positions match. It returns false otherwise.

Exercise: Write a program that reads 15 floating point numbers from the keyboard, and stores these numbers in an array. Print a message indicating the largest array element and the smallest array element.

Searching Arrays

Search Algorithms
• Linear Search
• Binary Search
Searching - locating a particular value (the key) in an array

Linear Search

• works well for small arrays or unsorted arrays
• looks at each entry, starting with first, until search key is found or end of array is reached
• Returns either the index of the key, or a negative value if the key does not appear in the array

public int linearSearch(int[ ] theArray, int key)
{
for(int i = 0; i < array.length; i++)
if(array[i] = = key) return i;
return -1;
}

Algorithm Analysis:
If the array elements are unsorted, then on average the linear search algorithm will compare the key to half the array elements.

So for an array of size n, linear search does n/2 comparisons in the average case.

Binary Search

• requires a sorted array - the algorithm fails completely on unsorted arrays
• eliminates half of the remaining array elements from consideration after each comparison
• Searches the way you would search for a person's phone number in a phone book:
• Compares the middle of the array elements to the key
• If they are equal, return index
• If not, and search key < middle array element, search 1st half of the array
• Else search second half of the array
Example:
Search for key = 40 in array containing 2, 5, 7, 10, 15, 31, 40, 55

public int binarySearch(int[ ] array, int key)
{
int low = 0, high = array.length - 1;

while(low <= high) // Search elements in positions low to high
{
int mid = (low + high)/2; // index of the middle element
if(array[mid] = = key)  // compare middle element in the search range to the key
return mid
else if(array[mid] < key)  // Search top half
low = mid + 1;
else // Search bottom half
high = mid - 1;
}
return -1;
}