CS1103-programming2 Unit 1 Assignment

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

/**

* Runtime of the Selection sort is:0.005 Seconds

* Runtime of the In Built Sort method: 0.0 Seconds

* This time is for 1000 elements

*/

import java.util.Arrays;

import java.util.Scanner;
public class BenchmarkingSortingAlgorithms {

private static Scanner scan;

public static void selectionSort(int arr[])

int n = arr.length;

// One by one move boundary of the unsorted subarray


for (int i = 0; i < n-1; i++)

// Find the minimum element in the 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

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

}
}

public static void printArrayBySelectionSort(int[] arr) {

for(int i=0;i<arr.length;i++) {

System.out.print(arr[i]+" ");

public static void sortByInBuilt(int arr[]) {


Arrays.sort(arr);

public static void main(String[] args) {

scan = new Scanner(System.in);

System.out.println("Enter the limit of the array:");

int limit = scan.nextInt();


int[] arr = new int[limit];

for(int i = 0;i<arr.length;i++) {

arr[i] = (int) (Math.random() * 100);

long startTime = System.currentTimeMillis();

selectionSort(arr);
long runTime = System.currentTimeMillis() - startTime;

System.out.println("\nRun time of the Selection sort is:"+runTime/1000.0+" Seconds");

long startTime1 = System.currentTimeMillis();

sortByInBuilt(arr);

long runTime1 = System.currentTimeMillis()-startTime1;

System.out.println("\nRun time of the In Built Sort method: "+runTime1/1000.0+" Seconds");


printArrayBySelectionSort(arr);

----------------------

output

---------

Enter the limit of the array:

50

Run time of the Selection sort is:0.0 Seconds


Run time of the In Built Sort method: 0.0 Seconds

0 1 1 2 14 16 16 17 17 18 23 23 24 25 28 28 29 29 31 32 37 37 38 38 39 40 41 42 56 58 60 62 63 67 71 72
74 76 77 77 79 79 81 86 89 94 94 95 96 96

-----------------------------------------------

Enter the limit of the array:

1000

Run time of the Selection sort is:0.011 Seconds

Run time of the In Built Sort method: 0.001 Seconds

---------------------------------

Enter the limit of the array:

10000
Runtime of the Selection sort is:0.084 Seconds

Runtime of the In Built Sort method: 0.005 Seconds

-----------------------------------

You might also like