1. Given an integer array A 17,4,8, 2,5,3,9 a) Write your own Java source code n
ID: 3597215 • Letter: 1
Question
1. Given an integer array A 17,4,8, 2,5,3,9 a) Write your own Java source code named SelectionSort.java to implement Selection Sort algorithm on the array A. Please finish your code in the following template, where "XXXSort" is replaced with "SelectionSort". b) Write your own Java source code named InsertSort.java to implement Insertion Sort algo- rithm on the array A. Please also public class XXXSort public static void main) int [ ] A= {7, 4, 8, 2, 5, 3, 9); sort (A) show (A)i // display the sorted result A public static void sort (int[] A) public static void show (intI] A) // add all other functions you needExplanation / Answer
SelectionSort.java
public class SelectionSort {
public static void main(String[] args) {
int[] A = {7,4,8,2,5,3,9};
sort(A);
show(A);
}
public static void show(int[] A) {
for(int i=0;i<A.length;i++) {
System.out.print(A[i]+" ");
}
System.out.println();
}
public static int[] sort(int[] A){
for (int i = 0; i < A.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < A.length; j++)
if (A[j] < A[index])
index = j;
int smallerNumber = A[index];
A[index] = A[i];
A[i] = smallerNumber;
}
return A;
}
}
Output:
2 3 4 5 7 8 9
InsertionSort.java
public class InsertionSort {
public static void main(String[] args) {
int[] A = {7,4,8,2,5,3,9};
sort(A);
show(A);
}
public static void show(int[] A) {
for(int i=0;i<A.length;i++) {
System.out.print(A[i]+" ");
}
System.out.println();
}
public static void sort(int []list){
int n = list.length;
for (int j = 1; j < n; j++) {
int key = list[j];
int i = j-1;
while ( (i > -1) && ( list[i] > key ) ) {
list[i+1]= list[i];
i--;
}
list[i+1] = key;
}
}
}
Output:
2 3 4 5 7 8 9
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.