A. Notes
We mentioned int[] b = a; will not create a new copy of array a, so how do we copy an array?
class Main {
// a method to copy an array, it returns the copy as a new array
public static int[] copyArr(int[] arr){
int[] y = new int[arr.length];
for(int i=0;i<arr.length;i++){
y[i]=arr[i];
}
return y;
}
public static void main(String[] args) {
int[] x = {1, 2, 3, 4, 5};
int[] a = copyArr(x); // passing array x as the parameter, returning array is saved in a
// print a
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
Another example to take two arrays as parameters
class Main {
//merge two arrays
//if a={1,2,3,4,5}, b={-1, -2, -3}
//return {1,2,3,4,5,-1.-2,-3}
public static int[] merge(int[]a, int[]b){
int[] y = new int[a.length+b.length];
for(int i=0;i<y.length;i++){
if(i<a.length){
y[i]=a[i];
}else{
y[i]=b[i-a.length];
}
}
return y;
}
public static void main(String[] args) {
int[] x = {1, 2, 3, 4, 5};
int[] y = {-1, -2, -3, -4, -5};
int[] a = merge(x, y);// passing array x and y as parameters, returning array is saved in a
// print a
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
B. Exercises:
Implement the five methods below, then test them in main().
class Main {
/*reverse an array
* for instance, arr={1,2,3,4,5,6,7,8}
* the method should return {8,7,6,5,4,3,2,1}
*/
public static int[] reverse(int[] arr){
//Add your implementation here
}
/* return the index of the maximum element in an array
* for instance, arr={12, 90, -9, -234, 0, 8}
* the method should return 1
*/
public static int maxInd(int[] arr){
//Add your implementation here
}
/* return the index of the minimum element in an array
* for instance, arr={12, 90, -9, -234, 0, 8}
* the method should return 3
*/
public static int minInd(int[] arr){
//Add your implementation here
}
/* return the index of the first element that is 0
* for instance, arr={12, 90, -9, -234, 0, 8}
* the method should return 4
*/
public static int zeroInd(int[] arr){
//Add your implementation here
}
/*return a new array that has the common elements of a * and b. If there is no common element, returns null
* for instance, a={1,2,3,4,5,6,7,8}, b={5,6,7,-9,10,1}
* the method should return {5,6,7,1}
*/
public static int[] common(int[] a, int[] b){
//Add your implementation here
}
public static void main(String[] args) {
int[] x = {1, 2, 3, 4, 5};
int[] y = {-1, -2, 3, -4, 5};
int[] a = common(x, y);
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}