Skip to content

Commit 8e47ae2

Browse files
authored
Merge pull request #1319 from CodingCookieRookie/master
Addition of Binary Search Algorithm and modification of Selection Sort
2 parents c8ef1fd + 6818098 commit 8e47ae2

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

Searches/Perfect BinarySearch

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
static int binarySearch(int[] arr, int target) {
2+
int low = 0 ;
3+
int high = arr.length - 1 ;
4+
5+
while(low <= high) {
6+
int mid =(low + high) / 2;
7+
8+
if(arr[mid] == target) {
9+
return mid;
10+
}
11+
else if(arr[mid] > target) {
12+
high = mid - 1;
13+
}
14+
else {
15+
low = mid + 1;
16+
}
17+
18+
}
19+
return -1;
20+
}
21+

Sorts/SelectionSort.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@
88

99
public class SelectionSort implements SortAlgorithm {
1010

11+
/**
12+
* This method swaps the two elements in the array
13+
* @param arr, i, j The array for the swap and
14+
the indexes of the to-swap elements
15+
*/
16+
public void swap(T[] arr, int i, int j) {
17+
T temp = arr[i];
18+
arr[i] = arr[j];
19+
arr[j] = temp;
20+
}
21+
1122
/**
1223
* This method implements the Generic Selection Sort
1324
*
@@ -22,14 +33,14 @@ public <T extends Comparable<T>> T[] sort(T[] arr) {
2233
int min = i;
2334

2435
for (int j = i + 1; j < n; j++) {
25-
if (SortUtils.less(arr[j], arr[min])) {
36+
if (arr[min].compareTo(arr[j]) < 0) {
2637
min = j;
2738
}
2839
}
2940

3041
// Swapping if index of min is changed
3142
if (min != i) {
32-
SortUtils.swap(arr, i, min);
43+
swap(arr, i, min);
3344
}
3445
}
3546

0 commit comments

Comments
 (0)