In: Computer Science
Create a Java Application that implements a Selection sort algorithm to sort an array of 20 unsorted numbers. You should initiate this array yourself and first output the array in its original order, then output the array after it has been sorted by the selection sort algorithm. Create a second Java Application that implements an Insertion sort algorithm to sort the same array. Again, output the array in its original order, then output the array after it has been sorted by the insertion sort algorithm.
Selection Sort
public class SelectionSort {
/* Selection Sort function */
public static void sort(int arr[]){
int N = arr.length;
int i, j, pos, temp;
for (i = 0; i < N - 1; i++) {
pos = i;
for (j = i + 1; j < N; j++) {
if (arr[j] < arr[pos]) {
pos = j;
}
}
temp = arr[i];
arr[i] = arr[pos];
arr[pos] = temp;
}
}
static void printArray(int arr[]) {
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String[] args) {
int arr[]={121,74,14,66,98,20,53,21,29,49,54,76,54,87,99,14,54,76,8,12};
System.out.println("Original Array: ");
printArray(arr);
sort(arr);
System.out.println("Sorted Array: ");
printArray(arr);
}
}
Insertion Sort
public class InsertionSort {
/* Function to sort array using insertion sort */
static void sort(int values[]) {
int n = values.length;
for (int i = 1; i < n; ++i) {
int key = values[i];
int j = i - 1;
while (j >= 0 && values[j] > (key)) {
values[j + 1] = values[j];
j = j - 1;
}
values[j + 1] = key;
}
}
/* A utility function to print array of size n */
static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[]) {
int arr[]={121,74,14,66,98,20,53,21,29,49,54,76,54,87,99,14,54,76,8,12};
System.out.println("Original Array: ");
printArray(arr);
sort(arr);
System.out.println("Sorted Array: ");
printArray(arr);
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME