-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingI.java
More file actions
100 lines (76 loc) · 2.68 KB
/
Copy pathSortingI.java
File metadata and controls
100 lines (76 loc) · 2.68 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
public class SortingI{
// Selection Sort: O(n^2) time complexity in all cases, O(1) space complexity
public static void selectionSort(int[] arr){
for(int i = 0;i < arr.length - 1;i++){ //n-1 passes
int min = i; //assume first index of unsorted part is min
for(int j = i+1;j < arr.length ;j++){ //traverse the unsorted part hence j = i+1
if(arr[j] < arr[min]){ //compare with min
min = j; //update min index
}
}
int temp = arr[i]; //swap arr[i] and arr[min]
arr[i] = arr[min];
arr[min] = temp;
}
}
// Bubble Sort : O(n^2) time complexity in worst case and average case, O(1) space complexity
// O(n) time complexity in best case when array is already sorted that why we use a swapped flag
public static void bubbleSort(int[] arr){
for(int i = 0;i < arr.length;i++){
boolean isSorted = true;
for(int j = 1;j< arr.length - i;j++){
if(arr[j-1] > arr[j]){
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
isSorted = false;
}
}
if(isSorted){
break;
}
}
}
public static void swap(int[] arr,int a,int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
//Insertion Sort: O(n^2) time complexity in worst and average case, O(1) space complexity
//O(n) time complexity in best case when array is already sorted because we only do n comparisons and no swaps
public static void insertionSort(int[] arr){
for(int i = 0;i < arr.length;i++){
int j = i;
while(j > 0 && arr[j-1]>arr[j]){
swap(arr,j-1,j);
j--;
}
}
/*
for(int i = 1;i < arr.length;i++){
int key = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] > key){
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
*/
}
public static void main(String[] args) {
//Selection Sort:
int[] arr = new int[]{5,4,6,2,7};
for(int idx = 0;idx < arr.length;idx++){
System.out.print(arr[idx] + " ");
}
//selectionSort(arr);
//bubbleSort(arr);
insertionSort(arr);
System.out.println("");
for(int idx =0;idx < arr.length;idx++){
System.out.print(arr[idx] + " ");
}
System.out.println("");
}
}