Merge pull request #1319 from CodingCookieRookie/master
Addition of Binary Search Algorithm and modification of Selection Sort
This commit is contained in:
commit
8e47ae22e7
21
Searches/Perfect BinarySearch
Normal file
21
Searches/Perfect BinarySearch
Normal 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;
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user