Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b31c720

Browse files
committed
FEAT Implemented recursive binary search method
1 parent 83a558d commit b31c720

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎src/PracticeAlgorithms.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import java.util.Arrays;
12
import java.util.HashMap;
23
import java.util.Random;
34

@@ -131,6 +132,30 @@ public static long fact(int N) {
131132
return N * fact(N - 1);
132133
}
133134

135+
/**
136+
* static method that calls rank to binary search for "key"
137+
* */
138+
public static int binarySearch(int key, int[] array) {
139+
Arrays.sort(array); // we need the array to be sorted
140+
return rank(key, array, 0, array.length - 1);
141+
}
142+
143+
144+
/**
145+
* static recursive method that implements binary search
146+
* */
147+
public static int rank(int key, int[] array, int minIndex, int maxIndex) {
148+
if (minIndex > maxIndex) return -1;
149+
int midIndex = minIndex + (maxIndex - minIndex) / 2;
150+
151+
if (array[midIndex] == key) return midIndex;
152+
153+
if (array[midIndex] < key)
154+
return rank(key, array, midIndex + 1, maxIndex);
155+
else
156+
return rank(key, array, minIndex, maxIndex - 1);
157+
}
158+
134159

135160
public static void main(String[] args) {
136161
Random generator = new Random();
@@ -142,6 +167,19 @@ public static void main(String[] args) {
142167
boolean[][] testTwoDmBooleanArray = new boolean[3][2];
143168
int[][] testIntMatrix = new int[3][2];
144169

170+
int[] testIntArray = new int[10];
171+
172+
testIntArray[0] = 5;
173+
testIntArray[1] = 7;
174+
testIntArray[2] = 6;
175+
testIntArray[3] = 9;
176+
testIntArray[4] = 3;
177+
testIntArray[5] = 8;
178+
testIntArray[6] = 2;
179+
testIntArray[7] = 4;
180+
testIntArray[8] = 1;
181+
testIntArray[9] = 10;
182+
145183
testTwoDmBooleanArray[0][0] = true;
146184
testTwoDmBooleanArray[0][1] = false;
147185
testTwoDmBooleanArray[1][0] = false;
@@ -189,5 +227,9 @@ public static void main(String[] args) {
189227

190228
System.out.printf("31!: %d\n", fact(31)); // N > 31 causes overflow
191229
System.out.println();
230+
231+
System.out.println("- Binary Search: key = 5");
232+
System.out.println(binarySearch(5, testIntArray));
233+
System.out.println();
192234
}
193235
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /