// Your name here!
public class HW8 {
/**
* Print list[i..j] on one line, separated by spaces and surrounded by [ and ].
* @param list the sorted array.
* @param i the index of the start of the range to be printed.
* @param j the index of the end of the range to be printed.
*/
public static void print(int[] list, int i, int j) {
// copy code here from your Lab 8
}
/**
* (4 points)
* Return the maximum element in list[i..j]
* Precondition: j>=i
* @param list the array.
* @param i the index of the start of the range
* @param j the index of the end of the range
* @return the maximum element
*/
public static int max(int[] list, int i, int j) {
return -1;
}
/**
* (4 points)
* Return the position of the maximum element in list[i..j]
* Precondition: j>=i
* @param list the array.
* @param i the index of the start of the range
* @param j the index of the end of the range
* @return the index of the maximum element
*/
public static int maxPos(int[] list, int i, int j) {
return -1;
}
/**
* (4 points)
* swap the position of elements i and j
* Precondition: i,j vaild indices
* @param list the array.
* @param i the index of the start of the range
* @param j the index of the end of the range
*/
public static void swap(int[] list, int i, int j) {
}
/**
* (4 points)
* Return the subarray list[i..j] as a new array: list2[0..(j-i)]
* Precondition: j>=i
* @param list the array.
* @param i the index of the start of the range
* @param j the index of the end of the range
* @return the new array: list2[0..(j-i)]
*/
public static int[] subarray(int[] list, int i, int j) {
return null;
}
/**
* (4 points)
* Reverse the order of elements in the array in place
* using no additional arrays
* @param list the array.
*/
public static void reverse(int[] list, int i, int j) {
}
/**
* Extra Credit (5 points)
* Return the number of unique elements in list[i..j]
* return 0 if j < i
* @param list the array.
* @param i the index of the start of the range
* @param j the index of the end of the range
* @return the number of unique elements
*/
public static int countUnique(int[] list, int i, int j) {
// Hint: use two nested loops: one counting up, the other counting down
return -1;
}
/**
* Test the various methods in this class.
*/
public static void main(String[] args) {
// 0 1 2 3 4 5 6 7 8 9
int[] a = new int[] {3,1,4,5,9,2,0,8,7,6};
print(a, 0, 9); // Result: [3 1 4 5 9 2 0 8 7 6]
int max = max(a,0,9);
System.out.println(max); // 9
int pos = maxPos(a,0,9);
System.out.println(pos); // 4
max = max(a,5,9);
System.out.println(max); // 8
pos = maxPos(a,5,9);
System.out.println(pos); // 7
swap(a,0,9);
print(a, 0, 9); // Result: [6 1 4 5 9 2 0 8 7 3]
int b[] = subarray(a,4,7);
print(b, 0, 3); // Result: [9 2 0 8]
reverse(b,0,3);
print(b, 0, 3); // Result: [8 0 2 9]
// extra credit
int c[] = new int[] {0,0,1,1,0,0,2,2,3,0,0};
int m = countUnique(c, 0, 10);
System.out.println(m); // 4
}
}
|