I want to compare the time difference (Time required for..) Bubble Sort, Insertion Sort, and Selection Sort using Monte Carlo Simulation and output the time differences using Java.
I am still a beginner in java and don't understand completely how to use monte carlo simulation.
These are the sorting programs I want to use monte carlo to compare the time differential:
Bubble Sort:
import java.util.Arrays;
import java.util.Scanner;
public class sort {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Number of elements in array: ");
int n = in.nextInt();
int []a = new int[n];
System.out.println("Enter integer values: ");
for(int i=0; i<a.length; i++)
{
a[i]=in.nextInt();
}
System.out.println("UnSorted array: "+ Arrays.toString(a));
for(int i=0; i<n; i++) {
for(int j=1; j<n; j++) {
if(a[j-1]>a[j]) {
int temp = a[j-1];
a[j-1]=a[j];
a[j]=temp;
}
}
}
System.out.println("Sorted array: "+ Arrays.toString(a));
//Time Complexity: O(n*n)
//Space Complexity: O(1)
}
}
Output:
Enter the number of elements of array
5
Enter the integer array
-2
4
22
45
-60
UnSorted array: [-2, 4, 22, 45, -60]
Sorted array: [-60, -2, 4, 22, 45]
Selection Sort:
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
// 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;
// Swap the found minimum element with the first
// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver code to test above
public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}
Output:
Sorted array
11 12 22 25 64
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[])
{
int arr[] = {12, 11, 13, 5, 6};
InsertionSort ob = new InsertionSort();
ob.sort(arr);
printArray(arr);
}
}
Output:
5 6 11 12 13