-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectionSort_InsertionSort.java
61 lines (60 loc) · 1.93 KB
/
SelectionSort_InsertionSort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.*;
public class SelectionSort_InsertionSort {
static void selectionSort(int arr[]){
long startSS = System.nanoTime();
System.out.println("Selection Sort: ");
int min;
for(int i=0; i<arr.length-1; i++){
System.out.print("Pass "+ (i+1) + ": ");
min = i;
for(int j=i+1; j<arr.length; j++){
if(arr[j]<arr[min])
min = j;
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
print(arr);
}
long endSS = System.nanoTime();
System.out.println("Elapsed time = " + (endSS - startSS));
}
static void insertionSort(int arr[]){
long startIS = System.nanoTime();
System.out.println("Insertion Sort: ");
int j;
for(int i=1; i<arr.length; i++){
System.out.print("Pass "+ i + ": ");
j = i-1;
int key = arr[i];
while(j>=0 && arr[j]>key){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
print(arr);
}
long endIS = System.nanoTime();
System.out.println("Elapsed time = " + (endIS - startIS));
}
static void print(int arr[]){
for(int i=0; i<arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements to sort: ");
int n = sc.nextInt();
int arr1[] = new int[n];
int arr2[] = new int[n];
System.out.println("Enter elements: ");
for(int i=0; i<n; i++){
arr1[i] = sc.nextInt();
arr2[i] = arr1[i];
}
selectionSort(arr1);
insertionSort(arr2);
}
}