Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit f8a35a2

Browse files
author
Ram swaroop
committed
code done + unit tested
1 parent ba1747a commit f8a35a2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package me.ramswaroop.arrays;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 9/8/15
8+
* @time: 11:34 PM
9+
*/
10+
public class FixedPoint {
11+
12+
/**
13+
* Finds the FIXED POINT in an array {@param a} of n distinct integers sorted
14+
* in ascending order. If there is no fixed point it returns -1.
15+
* FIXED POINT in an array is an index i such that arr[i] is equal to i. Note that
16+
* integers in array can be negative.
17+
*
18+
* @param a
19+
* @return
20+
*/
21+
public static int findFixedPoint(int[] a) {
22+
int low = 0, high = a.length - 1, mid;
23+
while (low <= high) {
24+
mid = (low + high) / 2;
25+
if (a[mid] == mid) {
26+
return mid;
27+
} else if (a[mid] > mid) {
28+
high = mid - 1;
29+
} else {
30+
low = mid + 1;
31+
}
32+
}
33+
return -1;
34+
}
35+
36+
public static void main(String a[]) {
37+
System.out.println(findFixedPoint(new int[]{-10, -5, 0, 3, 7}));
38+
System.out.println(findFixedPoint(new int[]{0, 2, 5, 8, 17}));
39+
System.out.println(findFixedPoint(new int[]{-10, -5, 3, 4, 7, 9}));
40+
}
41+
}

0 commit comments

Comments
 (0)