-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingAlgo.java
More file actions
150 lines (97 loc) · 2.87 KB
/
SortingAlgo.java
File metadata and controls
150 lines (97 loc) · 2.87 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
public class Solution {
//Merge Sort
public static int[] merge(int arr1[], int arr2[]) {
int m = arr1.length;
int n = arr2.length;
int arr[] = new int[m+n];
int i =0;
int j=0;
int k=0;
while(i<m && j<n){
if(arr1[i] <= arr2[j]){
arr[k] = arr1[i];
i++;
k++;
}else{
arr[k] = arr2[j];
j++;
k++;
}
}
while(i<m){
arr[k] = arr1[i];
i++;
k++;
}
while(j<n){
arr[k] = arr2[j];
j++;
k++;
}
return arr;
}
// Insersion Sort
public static void insertionSort(int[] arr) {
//Your code goes here
for(int i=1; i<arr.length; i++){
int j = i-1;
int temp = arr[i];
while(j >= 0 && arr[j] > temp ){
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
//Bubble Sort
public static void bubbleSort(int[] a){
//Your code goes here
int n = a.length;
for(int i =0; i<n-1; i++) {
for(int j=0; j<n-1; j++) {
if(a[j] > a[j+1]) {
int temp =a[j];
a[j] = a[j+1];
a[j +1] = temp;
}
}
}
}
// Selection sort
public static void selectionSort(int[] arr) {
int n = arr.length;
for(int i=0; i<n-1; i++){
int min = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = i; j<n; j++){
if(arr[j] < min){
min = arr[j];
minIndex = j;
}
}
//Swap min value
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static int binarySearch(int[] arr, int x) {
//Your code goes here
// Binary Search
int n = arr.length;
int s=0, e = n-1;
int mid = s + (e-s)/2;
while(s<=e){
if(arr[mid] == x){
return mid;
}
if(arr[mid] < x){
s = mid +1;
}else if(arr[mid] > x){
e = mid -1;
}
mid = s + (e-s)/2;
}
return -1;
}
}