In: Computer Science
All code in JAVA please
1. Implement Insertion Sort
2. Implement Selection Sort
*For problem 1 and 2, please:
a. Let the program generate a random array.
b. Output both the original random array and the sorted version of
it
import java.util.Random;
// Java program for implementation of Insertion Sort
class InsertionSort {
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[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[])
{
// create instance for Random class
Random rand = new Random();
int size = rand.nextInt(1000); //To generate random nos from 1 to
999
int[] arr = new int[size]; //Delcare array
for (int i=0; i<size; i++){
int n = rand.nextInt(1000);
arr[i] = n;
}
System.out.print("Random array is ");
printArray(arr);
InsertionSort ob = new InsertionSort();
ob.sort(arr);
System.out.print("\nSorted array is ");
printArray(arr);
}
}
2.Selection Sort
// Java program for implementation of Selection Sort
import java.util.Random;
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
// move boundary of unsorted
subarray
for (int i = 0; i < n-1;
i++)
{
// To find min
in unsorted arr
int min_idx =
i;
for (int j =
i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap Min
ele with first ele
int temp =
arr[min_idx];
arr[min_idx] =
arr[i];
arr[i] =
temp;
}
}
// Function Prints the array
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
// create instance for Random class
Random rand = new Random();
int size = rand.nextInt(1000); //To generate random nos from 1 to
999
int[] arr = new int[size]; //Delcare array
for (int i=0; i<size; i++){
int n = rand.nextInt(1000);
arr[i] = n;
}
System.out.println("Random array
");
printArray(arr);
SelectionSort ob = new
SelectionSort();
ob.sort(arr);
System.out.println("Sorted
array");
ob.printArray(arr);
}
}
Any doughts let me know in comments ..
ThankYou :-)