Merge pull request #1319 from CodingCookieRookie/master

Addition of Binary Search Algorithm and modification of Selection Sort
This commit is contained in:
Sombit Bose 2020-05-20 12:08:23 +05:30 committed by GitHub
commit 8e47ae22e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 2 deletions

View File

@ -0,0 +1,21 @@
static int binarySearch(int[] arr, int target) {
int low = 0 ;
int high = arr.length - 1 ;
while(low <= high) {
int mid =(low + high) / 2;
if(arr[mid] == target) {
return mid;
}
else if(arr[mid] > target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}

View File

@ -8,6 +8,17 @@ package Sorts;
public class SelectionSort implements SortAlgorithm {
/**
* This method swaps the two elements in the array
* @param arr, i, j The array for the swap and
the indexes of the to-swap elements
*/
public void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* This method implements the Generic Selection Sort
*
@ -22,14 +33,14 @@ public class SelectionSort implements SortAlgorithm {
int min = i;
for (int j = i + 1; j < n; j++) {
if (SortUtils.less(arr[j], arr[min])) {
if (arr[min].compareTo(arr[j]) < 0) {
min = j;
}
}
// Swapping if index of min is changed
if (min != i) {
SortUtils.swap(arr, i, min);
swap(arr, i, min);
}
}