In: Computer Science
For this assignment, find out how to do a bubble sort, selection sort, or insertion sort in Java. You have the option to choose but you must label (with comments) the algorithm you choose to implement. Convert that algorithm to a generic algorithm and constraint it to only using numerics. Your method should accept an array as a parameter and sort the content of the array. If you wish, you can throw an exception if the contents of the array passed are non-numeric. Create a main method that demonstrates this generic array receiving numeric arrays and sorting them appropriately. The package name should be genericSort.
CODE IN JAVA:
import java.util.Scanner;
public class Sortings {
static void bubblesort(int arr[]) {
int n = arr.length;
int temp;
boolean swap ;
int swapCount = 0 ;
for(int i=0;i<n;i++) {
swap = true;
for(int j=0;j<n-1;j++) {
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j]= arr[j+1];
arr[j+1]=temp;
swap = false;
swapCount += 1 ;
}
}
if(swap)
break;
}
System.out.println("Total number of swappings done by bubblesort:"+swapCount);
}
static void selectionsort(int arr[]) {
int n = arr.length;
int swapCount = 0 ;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
swapCount += 1 ;
}
}
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
System.out.println("Total number of swappings done by insertionSort:"+swapCount);
}
static void insertionsort(int arr[]) {
int n = arr.length;
int swapCount = 0 ;
for (int i=1; i<n; ++i)
{
int key = arr[i];
int j = i-1;
while (j>=0 && arr[j] > key)
{
arr[j+1] = arr[j];
j = j-1;
swapCount += 1 ;
}
arr[j+1] = key;
}
System.out.println("Total number of swappings done by insertionSort:"+swapCount);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array:");
int n = sc.nextInt();
System.out.println("Enter the elements of the array:");
int arr[] = new int[n];
for(int i=0;i<n;i++)
arr[i] = sc.nextInt();
System.out.println("\n1.Bubblesort");
System.out.println("2.Insertionsort");
System.out.println("3.Selectionsort");
System.out.println("\nEnter your choice:");
int choice = sc.nextInt();
switch(choice) {
case 1:
bubblesort(arr);
System.out.println("Now your array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ") ;
System.out.println();
break;
case 2:
insertionsort(arr);
System.out.println("Now your array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ") ;
System.out.println();
break;
case 3:
selectionsort(arr);
System.out.println("Now your array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+" ") ;
System.out.println();
break;
default:
System.out.println("invalid choice....");
}
}
}
OUTPUT: