Question: Checking Java code and add comments. a) a class Homework (in a file Homework.java) b) a static method initializeArray that receives as a parameter an

Checking Java code and add comments.

a) a class Homework (in a file Homework.java)

b) a static method initializeArray that receives as a parameter an array of characters. Use a for loop and an if statement to put 'b' in the odd positions of the array and 'a' in the even positions.

c) a static method printArray that receives as a parameter an array of

characters. Use a for statements to print all the elements in the array.

d) a static method selectionSort that receives as a parameter an array of characters and order its elements in ascending order. Implement Selection Sort algorithm. It should be Selection Sort, not Bubble Sort, not Quick Sort, etc. If you do not remember selection sort, this link could be useful: https://www.geeksforgeeks.org/java-program-for-selection-sort/

e) a static recursive method named factorial that calculate and returns the factorial of a number. The method receives a number (integer number) as parameter.

CODE:

public class Homework {

public static void main(String[] arg) {

char[] a = {'a', 'b', 'c', 'd', 'x', 'y', '1', '2', '3', '4'};

char[] b = {'p', 'q', '9', '8', '7', '6'};

int[] c = {6, 0, 1};

// Testing initializeArray

printArray(a);

initializeArray(a);

printArray(a);

// Testing selectionSort

printArray(b);

selectionSort(b);

printArray(b);

// Testing factorial

System.out.println(factorial(5));

System.out.println(factorial(c[0]));

System.out.println(factorial(c[2]));

}

private static void initializeArray(char[] a) {

for (int i = 0; i < a.length; i++) {

if ((i + 1) % 2 == 0) {

a[i] = 'b';

} else {

a[i] = 'a';

}

}

}

private static void printArray(char[] a) {

for (int i = 0; i < a.length; i++) {

System.out.print(a[i] + " ");

}

System.out.println();

}

private static void selectionSort(char[] b) {

int minIndex;

char temp;

int SIZE = b.length;

for (int i = 0; i < SIZE - 1; i++) {

minIndex = i;

for (int j = i + 1; j < SIZE; j++) {

if (b[j] < b[minIndex]) {

minIndex = j;

}

}

if (minIndex != i) {

temp = b[i];

b[i] = b[minIndex];

b[minIndex] = temp;

}

}

}

private static int factorial(int num) {

int res = 0;

if (num == 0) {

res = 1;

} else if (num == 1) {

res = 1;

} else if (num > 1) {

if (num - 1 == 1) {

}

res = num * factorial(num - 1);

}

return res;

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!