Write a program named ProcessArray.java, and write two static methods as specifi
ID: 3854552 • Letter: W
Question
Write a program named ProcessArray.java, and write two static methods as specified in the following header: public static int[] oddArray(int[] arr) public static int[] evenArray(int[] arr) the oddArray method returns a sorted (in ascending order) array that contains all odd numbers in the argument array, and the evenArray method returns a sorted array that contains all even numbers in the argument array. For example, int[] arr={ 3, 8, 1, 9, 2}; ProcessArray.oddArray(arr) should return {1,3,9} ProcessArray.evenArray(arr) should return {2,8} KEEP ALL OF THE NAMES AS THEY ARE
Explanation / Answer
The java programming code is ,the name of the program is ProcessArray.java
package constructors;
import java.util.*;
public class ProcessArray
{
public static void main(String[] args) {
int[] arr = {3, 8, 1, 9, 2};
int[] res;
System.out.println(Arrays.toString(arr));
selectionSort(arr);
System.out.println(Arrays.toString(arr));
res = ProcessArray.oddArray(arr);
System.out.println(Arrays.toString(res));
res=ProcessArray.evenArray(arr);
System.out.println(Arrays.toString(res));
}
//method to sort numbers in an array
private static void selectionSort(int[] arr) {
// TODO Auto-generated method stub
for (int i = 0; i < arr.length - 1; i++) {
int index = 0;
for (int k = 0; k < arr.length - i; k++) {
if (arr[k] > arr[index]) {
index = k;
}
}
//swapping
int tmp = arr[index];
arr[index] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
//method to take array of odd numbers
public static int[] oddArray(int[] arr) {
int c = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 != 0) {
c++;
}
}
int[] arrayc = new int[c];
int ins=0;
for (int i = 0; i < arr.length; i++)
if (arr[i] % 2 != 0)
arrayc[ins++]=arr[i];
return arrayc;
}
//method to take array of even numbers
public static int[] evenArray(int[] arr) {
int c = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
c++;
}
}
int[] arrayc = new int[c];
int ins=0;
for (int i = 0; i < arr.length; i++)
if (arr[i] % 2 == 0)
arrayc[ins++]=arr[i];
return arrayc;
}
}
the output is:[3, 8, 1, 9, 2]
[1, 2, 3, 8, 9]
[1, 3, 9]
[2, 8]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.