I'm struggling to get my desired output below. This is what I have done so far, and I think I'm close to being done.
import java.util.Scanner;
public class sortedArrayBST {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
try {
if (n <= 0) {
input.close();
}
int m = input.nextInt();
if (m <= 0) {
input.close();
}
int[] s = new int[n];
int[] w = new int[m];
for (int i = 0; i < n; i++) {
s[i] = input.nextInt();
}
for (int i = 0; i < m; i++) {
w[i] = input.nextInt();
}
} catch (IllegalStateException e) {
}
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode parent;
TreeNode(int x) {
val = x;
}
}
public static TreeNode sortedArrayToBST(int[] num) {
if (num == null || num.length == 0)
return null;
int start = 0, end = num.length - 1;
TreeNode root = buildTree(num, start, end);
return root;
}
public static TreeNode buildTree(int[] num, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode node = new TreeNode(num[mid]);
node.left = buildTree(num, start, mid - 1);
node.right = buildTree(num, mid + 1, end);
return node;
}
}
I have to take user input such as:
4 // denotes number of elements in array S, variable n.
2 // number of elements in array W, variable m.
0 // 0, 25, 33, 77 are in S.
25
33
77
19 // 19 and 40 are in W.
40
Those numbers represent the sentence positions, so the ends of each sentence.
The output is
2 // 2 words of interest found, this value is always the same as W above
1 25 // start of the sentence with 1st occurrence of word of interest (end of previous sentence + 1) and end of the sentence (aka ".")
34 77 // so the previous sentence before this ended at position 33, so the next sentence started at 34, and it ends at 77.
IDK how to get this using a sorted array to a BST.
If I understand you correctly, I think what you're looking for, is a way to traverse the bst you constructed to print the output in the given format.
If that is the case, you can do an inorder traversal of the tree to achieve that.(Although, having a sorted array, constructing a bst out of it and then printing the bst in a sorted order is kind of an overkill don't you think?)
static boolean flag = false;
public static void inorderTraverse(TreeNode root){
if(root == null) return;
inorderTraverse(root.left);
if(flag){
System.out.print(root.val);
System.out.print("\n");
flag = false;
}
else{
flag = true;
System.out.print(root.val + 1 + " ");
}
inorderTraverse(root.right);
}
Related
I'm trying to output left and right indexes of the block in jump search algorithm, but I don't really know how to do it. Do you have any idea? The last block may be shorter so probably left border is going to be shorter than the others, so I can really picture a solution. When I'm declaring a new variable and I'm trying to update it in a loop, then outside of the loop it still has the old value and I really don't know why.
My code:
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
int[] array = new int[length];
for (int i = 0; i < array.length; i++) {
array[i] = scanner.nextInt();
}
int target = scanner.nextInt();
jumpSearch(array,target);
}
public static int jumpSearch(int[] array, int target) {
int currentRight = 0;
int prevRight = 0;
// If array is empty, the element is not found
if (array.length == 0) {
return -1;
}
// Check the first element
if (array[currentRight] == target) {
return 0;
}
// Calculating the jump length over array elements
int jumpLength = (int) Math.sqrt(array.length);
// Finding a block where the element may be present
while (currentRight < array.length - 1) {
// Calculating the right border of the following block
currentRight = Math.min(array.length - 1, currentRight + jumpLength);
if (array[currentRight] >= target) {
break; // Found a block that may contain the target element
}
prevRight = currentRight; // update the previous right block border
// If the last block is reached and it cannot contain the target value => not found
if ((currentRight == array.length - 1) && target > array[currentRight]) {
return -1;
}
/* Doing linear search in the found block */
// backwardSearch(array, target, prevRight, currentRight);
return 0;
}
public static int backwardSearch(int[] array, int target, int leftExcl, int rightIncl) {
for (int i = rightIncl; i > leftExcl; i--) {
if (array[i] == target) {
return i;
}
}
return -1;
}
}
Here is the code from the example that I linked to in my comment to your question. I added three lines to it. I added a the following comment to each line I added.
// ADDED THIS LINE
public class JumpSearch
{
public static int jumpSearch(int[] arr, int x)
{
int n = arr.length;
// Finding block size to be jumped
int step = (int)Math.floor(Math.sqrt(n));
// Finding the block where element is
// present (if it is present)
int prev = 0;
while (arr[Math.min(step, n)-1] < x)
{
prev = step;
step += (int)Math.floor(Math.sqrt(n));
if (prev >= n)
return -1;
}
// Doing a linear search for x in block
// beginning with prev.
int left = prev; // ADDED THIS LINE
int right = Math.min(step, n); // ADDED THIS LINE
while (arr[prev] < x)
{
prev++;
// If we reached next block or end of
// array, element is not present.
if (prev == Math.min(step, n))
return -1;
}
// If element is found
if (arr[prev] == x) {
System.out.printf("Found %d between %d and %d%n", x, left, right); // ADDED THIS LINE
return prev;
}
return -1;
}
// Driver program to test function
public static void main(String [ ] args)
{
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610};
int x = 55;
// Find the index of 'x' using Jump Search
int index = jumpSearch(arr, x);
// Print the index where 'x' is located
System.out.println("\nNumber " + x +
" is at index " + index);
}
}
When I run the above code, I get this output.
Found 55 between 8 and 12
Number 55 is at index 10
Is that what you are looking for?
I want to traverse over a given tree using in-order traversal. inserting the sorted array into the BST (keeping it the same shape)
This is my go:
public static BinTreeNode<Integer> ARR_TO_BST(BinTreeNode<Integer> root, int[] arr, int ind){
if (root.GetLeft() != null)
ARR_TO_BST(root.GetLeft(), arr, ind);
root.SetInfo(arr[ind]);
ind+=1;
if (root.GetRight() != null)
ARR_TO_BST(root.GetRight(), arr, ind);
return root;
The problem is that if the array is arr = {10,20,30,40,50,60}
and the tree is:
The return output is a tree that if I do an in-order traversal over it is: 10 20 10 20 10 20 ... and not 10 20 30 40 50 60
I need the output to be the same shape of the picture but with the values of arr the algorithm is to traverse -in order on the tree : left subtree - vertex - right subtree
but instead of reading the values we insert the values from arr to root
I would appreciate help! thank you
You never change ind. After the first call to ARR_TO_BST, it remains what it was before the call. Make ARR_TO_BST return the number of elements it placed:
if (root.GetLeft() != null)
ind = ARR_TO_BST(root.GetLeft(), arr, ind);
root.SetInfo(arr[ind]);
if (root.GetLeft() != null)
ind = ARR_TO_BST(root.GetLeft(), arr, ind + 1);
return ind;
and you should be all right.
You can use accomplish by keep tracking the index of each element to add it back to the result array
static class BST {
private class Node {
private Integer key;
private Node left, right;
private int index;
public Node(Integer key, int index) {
this.key = key;
this.index = index;
}
}
private Node root;
private int size = 0;
public void put(int[] arr) {
if (size >= arr.length)
return;
root = put(root, arr[size], size);
size++;
put(arr);
}
private Node put(Node node, int key, int index) {
if (node == null)
return new Node(key, index);
int cmp = Integer.valueOf(key).compareTo(node.key);
if (cmp < 0)
node.left = put(node.left, key, index);
else if (cmp > 0)
node.right = put(node.right, key, index);
else
node.key = key;
return node;
}
public int size() {
return size;
}
public int[] keys() {
int[] result = new int[size];
get(root, result, 0);
return result;
}
public void get(Node node, int[] result, int i) {
if (i >= result.length || node == null)
return;
result[node.index] = node.key;
get(node.left, result, ++i);
get(node.right, result, ++i);
}
}
, main
public static void main(String[] args) {
BST bst = new BST();
bst.put(new int[] { 10, 20, 5, 40, 1, 60, -10, 0 });
for (int num : bst.keys()) {
System.out.print(num + " ");
}
}
, output
10 20 5 40 1 60
Recently i attended one interview there they asked me to write a program like below,
A number chain is created by continously adding the square of the digits in a number
to form a new number untill its has been seen before.
example :
44 -> 32 -> 13-> 10-> 1
85->89->145->42->20->4->16->37->58->89
therefore any chain arrives at 1 or 89 will become stuck in endless loop.
what is most amazing is that every starting number will eventually arrive at 1 or 89.
write a program to count the starting number below 10000 will arrive at 89?
I wrote programs like below,
int num =44;
int array[] = new int[100];
int power=0;
while(num > 0)
{
int mod = num % 10;
int div = num /10;
int sum =(mod * mod) + (div * div);
num =sum;
System.out.print(" => "+sum);
if(array.equals(sum))
// should not use any functions like Arrays.asList(array).contains(sum);
return;
else
{
//System.out.println("else");
array[power++] =sum;
}
}
I know that above program not satisfy their requirements.Some one tell me good code snip to make them code satisfaction(If same question ask in future).?
Note : should not use any function or import. Only logic is need.
Maintain a cache of already calculated numbers. This will reduce the number of unnecessary iterations which were already calculated.
Let's do some math
From you example
44 -> 32 -> 13-> 10-> 1
85->89->145->42->20->4->16->37->58->89
You already know that the numbers 85, 89, 145, 42, 20, 4, 16, 37, 58 lead to 89 and 44, 32,13, 10, 1 don't.
In some case say calculating it for 11.
11 - 2 - 4
Now we already know 4 leads to 89 and so we skip all the other unnecessary iteration from
4 - 16 - 37 - 58 - 89 and also we now know that 11, 2also lead to 89.
So no the algorithm would be:
while(num > 0)
{
if(calculate[i] == 1)//which mean leads to 89
{
// dont calculate again
}
else
{
// num = // your squares logic
}
}
I read this as a recursive problem. I made the assumption that you only want to know the number of steps until 1 or 89 is reached.
The helper method, getDigits() is just for simplicity. The conversion to the String isn't technically necessary, but it makes the code simple.
public static void main(String[] args) {
int v = 9843;
int[] count = {0};
System.out.println("Number of steps: " + countSteps(v,count)[0]);
}
private static int[] countSteps(int initialValue, int[] count){
if(initialValue == 1 || initialValue == 89){
return count;
}
count[0]++;
int[] digits = getDigits(initialValue);
initialValue = 0;
for (int k : digits) {
initialValue += k * k;
}
countSteps(initialValue,count);
return count;
}
private static int[] getDigits(int i){
String s = Integer.toString(i);
int[] digits = new int[s.length()];
for(int j=0;j<s.length();j++){
digits[j] = s.charAt(j) - '0';
}
return digits;
}
If you are generating a sequence it makes sense to use an Iterable.
public static class SquaredDigitsSequence implements Iterable<Integer> {
int start;
SquaredDigitsSequence(int start) {
this.start = start;
}
#Override
public Iterator<Integer> iterator() {
return new SquaredDigitsIterator(start);
}
static class SquaredDigitsIterator implements Iterator<Integer> {
int last;
Set<Integer> seen = new HashSet<>();
SquaredDigitsIterator(int start) {
last = start;
seen.add(last);
}
#Override
public boolean hasNext() {
return !seen.contains(step());
}
#Override
public Integer next() {
last = step();
seen.add(last);
return last;
}
int step() {
int next = 0;
for (int x = last; x != 0; x /= 10) {
next += (x % 10) * (x % 10);
}
return next;
}
}
}
public void test() {
for (int i = 0; i < 100; i++) {
System.out.print(i + " ");
for (int x : new SquaredDigitsSequence(i)) {
System.out.print(x + " ");
}
System.out.println();
}
}
This prints all sequences up to 100 and does indeed include the two examples you posted but sadly it does not always terminate at 1 or 89.
class SquareDigits{
public static void main(String[] args){
System.out.println("Amount of numbers ending on 89: " + loop(10000));
}
public static int loop(int limit){
int cnt = 0;
for(int i = 1; i < limit; i++){
if(arriveAt89(i))
cnt++;
}
return cnt;
}
public static boolean arriveAt89(int num){
while(num != 89 && num != 1){
num = addSquares(num);
}
if(num == 89)
return true;
return false;
}
public static int addSquares(int n){
int sum = 0;
for(Character c : ("" + n).toCharArray()){
sum += Character.getNumericValue(c)*Character.getNumericValue(c);
}
return sum;
}
}
Assuming you're just after the amount of numbers that ends with 89.
This prints all numbers that end up in 89 below 89.
//array = boolean array to hold cache
//arr= list to store numbers in the chain that goes up to 89 used in setting cache
public static void main(String args[]) {
Boolean[] array = new Boolean[100];
Arrays.fill(array, Boolean.FALSE);
for(int i=2;i<89;i++){
checkChain(i,array);
}
for(int k=0;k<89;k++){
if(array[k]){System.out.println(k);}
}
}
private static void checkChain(int num,Boolean[] array) {
List<Integer> arr= new ArrayList<Integer>();
int initial = num;
int next;
do{
next=0;
arr.add(num);
while(num>0){
if(array[num] || num==89){
for(Integer j:arr){
array[j]=true;
}
break;
}
next = next+(num%10)*(num%10);
num=num/10;
}
num=next;
if(next<initial && array[next]){
array[initial]=true;
break;
}
}while((next>initial));
}
}
I tried to build a minHeap using java, this is my code:
public class MyMinHeap {
private ArrayList<Node> heap;
public MyMinHeap() {
heap = new ArrayList<Node>();
}
public MyMinHeap(ArrayList<Node> nodeList) {
heap = nodeList;
buildHeap();
}
public void buildHeap() {
int i = heap.size() / 2;
while (i >= 0) {
minHeapify(i);
i--;
}
}
public Node extractMin() {
if (heap.size() <= 0) return null;
Node minValue = heap.get(0);
heap.set(0, heap.get(heap.size() - 1));
heap.remove(heap.size() - 1);
minHeapify(0);
return minValue;
}
public String toString() {
String s = "";
for (Node n : heap) {
s += n + ",";
}
return s;
}
public void minHeapify(int i) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = i;
if (left < heap.size() - 1 && lessThan(left, smallest))
smallest = left;
if (right < heap.size() - 1 && lessThan(right, smallest))
smallest = right;
if (smallest != i) {
swap(smallest, i);
minHeapify(smallest);
}
}
private void swap(int i, int j) {
Node t = heap.get(i);
heap.set(i, heap.get(j));
heap.set(j, t);
}
public boolean lessThan(int i, int j) {
return heap.get(i)
.compareTo(heap.get(j)) < 0;
}
public static void main(String[] args) {
char[] chars = {'a', 'b', 'c', 'd', 'e', 'f'};
int[] freqs = {45, 13, 12, 16, 9, 5};
ArrayList<Node> data = new ArrayList<Node>();
for (int i = 0; i < chars.length; i++) {
data.add(new Node(chars[i], freqs[i]));
}
MyMinHeap heap = new MyMinHeap(data);
System.out.println("print the heap : " + heap);
for (int i = 0; i < chars.length; i++) {
System.out.println("Smallest is :" + heap.extractMin());
}
}
}
The output should be:5,9,12,13,16,45,
but what I got is : 9,13,12,16,45
I have debugged this but still can't figure out, anybody help? thanks a lot.
Insert :
When we insert into a min-heap, we always start by inserting the element at the bottom. We insert at the
rightmost spot so as to maintain the complete tree property.
Then, we "fix" the tree by swapping the new element with its parent, until we find an appropriate spot for
the element. We essentially bubble up the minimum element.
This takes 0 (log n) time, where n is the number of nodes in the heap.
Extract Minimum Element :
Finding the minimum element of a min-heap is easy: it's always at the top. The trickier part is how to remove
it. (I n fact, this isn't that tricky.)
First, we remove the minimum element and swap it with the last element in the heap (the bottommost,
rightmost element). Then, we bubble down this element, swapping it with one of its children until the minheap
property is restored.
Do we swap it with the left child or the right child? That depends on their values. There's no inherent
ordering between the left and right element, but you'll need to take the smaller one in order to maintain
the min-heap ordering.
public class MinHeap {
private int[] heap;
private int size;
private static final int FRONT = 1;
public MinHeap(int maxSize) {
heap = new int[maxSize + 1];
size = 0;
}
private int getParent(int position) {
return position / 2;
}
private int getLeftChild(int position) {
return position * 2;
}
private int getRightChild(int position) {
return position * 2 + 1;
}
private void swap(int position1, int position2) {
int temp = heap[position1];
heap[position1] = heap[position2];
heap[position2] = temp;
}
private boolean isLeaf(int position) {
if (position > size / 2) {
return true;
}
return false;
}
public void insert(int data) {
heap[++size] = data;
int currentItemIndex = size;
while (heap[currentItemIndex] < heap[getParent(currentItemIndex)]) {
swap(currentItemIndex, getParent(currentItemIndex));
currentItemIndex = getParent(currentItemIndex);
}
}
public int delete() {
int item = heap[FRONT];
swap(FRONT, size--); // heap[FRONT] = heap[size--];
heapify(FRONT);
return item;
}
private void heapify(int position) {
if (isLeaf(position)) {
return;
}
if (heap[position] > heap[getLeftChild(position)]
|| heap[position] > heap[getRightChild(position)]) {
// if left is smaller than right
if (heap[getLeftChild(position)] < heap[getRightChild(position)]) {
// swap with left
swap(heap[position], heap[getLeftChild(position)]);
heapify(getLeftChild(position));
} else {
// swap with right
swap(heap[position], heap[getRightChild(position)]);
heapify(getRightChild(position));
}
}
}
#Override
public String toString() {
StringBuilder output = new StringBuilder();
for (int i = 1; i <= size / 2; i++) {
output.append("Parent :" + heap[i]);
output
.append("LeftChild : " + heap[getLeftChild(i)] + " RightChild :" + heap[getRightChild(i)])
.append("\n");
}
return output.toString();
}
public static void main(String... arg) {
System.out.println("The Min Heap is ");
MinHeap minHeap = new MinHeap(15);
minHeap.insert(5);
minHeap.insert(3);
minHeap.insert(17);
minHeap.insert(10);
minHeap.insert(84);
minHeap.insert(19);
minHeap.insert(6);
minHeap.insert(22);
minHeap.insert(9);
System.out.println(minHeap.toString());
System.out.println("The Min val is " + minHeap.delete());
}
}
The problem is in your minHeapify function. You have:
public void minHeapify(int i) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = i;
if (left < heap.size() - 1 && lessThan(left, smallest))
smallest = left;
if (right < heap.size() - 1 && lessThan(right, smallest))
smallest = right;
Now, let's say that your initial array list is {3,2}, and you call minHeapify(0).
left = 2 * i + 1; // = 1
right = 2 * i + 2; // = 2
smallest = i; // 0
Your next statement:
if (left < heap.size() - 1 && lessThan(left, smallest))
At this point, left = 1, and heap.size() returns 2. So left isn't smaller than heap.size() - 1. So your function exits without swapping the two items.
Remove the - 1 from your conditionals, giving:
if (left < heap.size() && lessThan(left, smallest))
smallest = left;
if (right < heap.size() && lessThan(right, smallest))
smallest = right;
I am trying to put java code for fibonacci search with my understanding gained from
http://en.wikipedia.org/wiki/Fibonacci_search :
Let k be defined as an element in F, the array of Fibonacci numbers. n = Fm is the array size. If the array size is not a Fibonacci number, let Fm be the smallest number in F that is greater than n.
The array of Fibonacci numbers is defined where Fk+2 = Fk+1 + Fk, when k ≥ 0, F1 = 1, and F0 = 0.
To test whether an item is in the list of ordered numbers, follow these steps:
Set k = m.
If k = 0, stop. There is no match; the item is not in the array.
Compare the item against element in Fk−1.
If the item matches, stop.
If the item is less than entry Fk−1, discard the elements from positions Fk−1 + 1 to n. Set k = k − 1 and return to step 2.
If the item is greater than entry Fk−1, discard the elements from positions 1 to Fk−1. Renumber the remaining elements from 1 to Fk−2, set k = k − 2, and return to step 2.
The below is my code:
package com.search.demo;
public class FibonacciSearch {
static int[] a = {10,20,30,40,50,60,70,80,90,100};
static int required = 70;
static int m = 2;
static int p = 0;
static int q = 0;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FibonacciSearch fs = new FibonacciSearch();
fs.findm();
fibSearch(required);
}
private void findm(){
//here you have to find Fm which matches size of searching array, or which is close to it.
int n = a.length;
int fibCurrent = 1;
int fibPrev1 = 1;
int fibPrev2 = 0;
while(n > fibCurrent){
fibPrev2 = fibPrev1;
fibPrev1 = fibCurrent;
fibCurrent = fibPrev1 + fibPrev2;
m++;
}
p = m-1;
q = m-2;
}
public static int fibSearch(int no){
for(;;){
if(m == 0){
System.out.println("not found");
return -1;
}
int j = f(p);
if(no == a[j]){
System.out.println("found at "+p);
}else if(no < a[j]){
m = p;
p = m - 1;
q = m - 2;
}else if(no > a[j]){
m = q; // as per the step 6..
p = m-1;
q = m-2;
}
}
//return m;
}
public static int f(int val){
if(val == 2 || val == 1 || val == 0){
return 1;
}
return (f(val-1) + f(val-2));
}
}
Please correct me what I am doing wrong, and help me understand it clearly..
I have seen this Fibonacci Search and http://www.cs.utsa.edu/~wagner/CS3343/binsearch/searches.html but I am not able to understand..
while(n > fibCurrent){
fibPrev2 = fibPrev1;
fibPrev1 = fibCurrent;
fibCurrent = fibPrev1 + fibPrev2;
m++;
}
This part in the findm() function is actually comparing nth fibonacci number but according to algorithm it should be cumulative sum of the fibonacci numbers upto that point.
Rather you can search for the element in while loop of findm.
Finally I am able to solve the puzzle, that's stopping me..
I think the below code should help someone who are stuck as I did.
package com.search.demo;
public class FibonacciSearch {
int a[] = {10,20,30,40,50,60,70,80,90,100};
static FibonacciSearch fs;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
fs = new FibonacciSearch();
int location = fs.find(70);
if(location < 0){
System.out.println("number not found..");
}else{
System.out.println("found at location "+location);
}
}
private int find(int no){
int n = a.length;
int m = findFm(n); //m = Fm iff n is Fibonacci number else returns Fm+1
int p = fibSequenceIterative(m-1); //p = Fm-1, always a fibonacci number
int q = fibSequenceIterative(m -2); //q = Fm-2, always a fibonacci number
while(true){
if(no == a[m]){
return m;
}else if (no < a[m]){
if(q == 0){
return -(m - 1);// we crossed 0th index in array, number not found.
}
m = m - q; //moved to 1 step left towards a fibonacci num
int tmp = p;//hold this temporarily
p = q; //move p to 1 step left into another fibonacci num
q = tmp - q;//moved q to 1 step left....
}else if(no > a[m]){
if(p == 1){
return -m;//we reached 0th index in array again and number not found..
}
m = m + q;
p = p - q;
q = q - p;
}
}
}
private int findFm(int n){
int prev = 1;
int curr = 1;
int next = 0;
if(n == 0){
next = 0;
return -1;
}else if(n == 1 || n == 2){
next = 1;
return 1;
}else{
for(int i = 3; ; i++){
next = prev + curr;
prev = curr;
curr = next;
System.out.println("prev = "+prev+" curr = "+curr+" next = "+next);
if(n <= curr){
System.out.println("n = "+n+" curr = "+curr);
return i;
}
}
//return -1;//we should not get here..
}
}
/* Iterative method for printing Fibonacci sequence..*/
private int fibSequenceIterative(int n){
int prev = 1;
int curr = 1;
int next = 0;
if(n == 0){
next = 0;
//return 0;
}else if(n == 1 || n == 2){
next = 1;
//return 1;
}else{
for(int i = 3; i <= n; i++){
next = prev + curr;
prev = curr;
curr = next;
}
return next;
}
return next;
}
}
The bit of code what I am doing wrong is managing the indexes, which does influence the position of dividing the array at an index postion.
the m should be find first, to the value that matches n (size of array). if it doesn't match it should be the next value at which the F(x) will be > n. i.e., in my case size is 10 which doesn't match with any fibonacci number, so the next value in the fibonacci series is 13. and the index of i at which our condition satisfied is F(7) = 13 which is > 10. So m = 7
and now p and q are 2 consecutive fibonacci numbers which always determine the interval at which to divide the array.
read the below:
Take N = 54, so that N+1 = 55 = F[10]. We will be searching the sorted array: A[1], ..., A[54], inclusive. The array indexes are strictly between the two Fibonacci number: 0 < 55. Instead of the midpoint, this search uses the next Fibonacci number down from F[10] = 55, namely F[9] = 34. Instead of dividing the search interval in two, 50% on either side, we divide roughly by the golden ratio, roughly 62% to the left and 38% to the right. If y == A[34], then we've found it. Otherwise we have two smaller intervals to search: 0 to 34 and 34 to 55, not including the endpoints. If you have two successive Fibonacci numbers, it's easy to march backwards using subtraction, so that above, the next number back from 34 is 55 - 34 = 21. We would break up 0 to 34 with a 21 in the middle. The range from 34 to 55 is broken using the next Fibonacci number down: 34 - 21 = 13. The whole interval [34, 55] has length 21, and we go 13 past the start, to 34 + 13 = 47. Notice that this is not a Fibonacci number -- it's the lengths of all the intervals that are.(copied from http://www.cs.utsa.edu/~wagner/CS3343/binsearch/fibsearch.html)