Recursive binary search in an int array using only 1 parameter - java

How can i implement a recursive binary search in an int array using only 1 parameter in java ?
it tried but my code doesn't work. I implemented a class which its instances are objects having arrays and a count variable to detect how many elements are their in the array. any idea how can i implement the recursive binary search using only 1 parameter ?
public class LinearSortedArray {
int count;
int[] a;
public LinearSortedArray() {
count = 0;
}
public LinearSortedArray(int size) {
count = 0;
a = new int[size];
}
public static int[] copyingMethod(int startPoint, int endPoint,
LinearSortedArray arrayObj) {
int[] copyingArray = new int[endPoint - startPoint];
int j = startPoint;
for (int i = 0; i < copyingArray.length; i++) {
copyingArray[i] = arrayObj.a[j];
j++;
}
return copyingArray;
}
public int binarySearchRec(int x) {
if (count == 0) {
return -1;
}
int pivot = count / 2;
LinearSortedArray newArrayObj;
if (x > a[pivot]) {
newArrayObj = new LinearSortedArray(count - pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(pivot, count, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return pivot + newArrayObj.binarySearchRec(x);
} else if (x < a[pivot]) {
newArrayObj = new LinearSortedArray(pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(0, pivot, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return newArrayObj.binarySearchRec(x);
} else {
return pivot;
}
}
}
P.S.: The arrays are already sorted

Binary search really requires a range and a target value -- so if you're only passing one parameter, this has to be the target and this must encapsulate the array & range.
public class ArraySegment {
protected int[] array;
protected int boundLo;
protected int boundHi;
public class ArraySegment (int[] array) {
// entire array.
this( array, 0, array.length);
}
public class ArraySegment (int[] array, int lo, int hi) {
this.array = array;
this.boundLo = lo;
this.boundHi = hi;
}
public int binarySearch (int target) {
if (boundHi <= boundLo) {
return -1; // Empty; not found.
}
int pivot = (boundLo + boundHi) / 2;
int pivotEl = array[ pivot];
if (target == pivotEl) {
return pivot; // Found!
}
if (target < pivotEl) {
// recurse Left of pivot.
ArraySegment sub = new ArraySegment( array, boundLo, pivot);
return sub.binarySearch( target);
} else {
// recurse Right of pivot.
ArraySegment sub = new ArraySegment( array, pivot, boundHi);
return sub.binarySearch( target);
}
}
}
It's a little bit questionable what kind of result you should return -- there isn't a good answer with the question posed like this, as an "integer index" kinda defeats the purpose of the ArraySegment/ range wrapper, and returning an ArraySegment containing only the found value is also fairly useless.
PS: You really shouldn't be copying the array or it's contents, just passing round references to ranges on that array. Like java.lang.String is a range on a character array.

You could contrive a single-parameter by using the Value Object Pattern, where you pass one "wrapper" object, but the object has many fields.
For example:
class SearchParams {
int target;
int start;
int end;
SearchParams(t, s, e) {
target = t;
start = s;
end = e'
}
}
int search(SearchParams params) {
// some impl
return search(new SearchParams(params.target, a, b));
}
Technically, this is one parameter. Although it may not be in the spirit of the rules.

Related

Bug in recursive selection sort?

I am trying to implement selection sort recursively in java, but my program keeps throwing an ArrayIndexOutOfBounds exception. Not sure what I am doing wrong. Recursion is very hard for me. Please help! I am a beginner.
public static int[] selection(int[] array) {
return sRec(array, array.length - 1, 0);
}
private static int[] sRec(int[] array, int length, int current) {
if (length == current) { //last index of array = index we are at
return array; //it's sorted
}
else {
int index = findBig(array, length, current, 0);
int[] swapped = swap(array, index, length - current);
return sRec(swapped, length - 1, current);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
}
private static int findBig(int[] array, int length, int current, int biggestIndex) {
if (length == current) {
return biggestIndex;
}
else if (array[biggestIndex] < array[current]) {
return findBig(array, length, current + 1, current);
}
else {
return findBig(array, length, current + 1, biggestIndex);
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
Try changing this in your Swap method :
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
to this :
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
You have already gotten the value you want to assign to the array , when you add that to the array it is searching in that specific index ,
For Example :
You wanted to enter the value 8 to your Array
Instead of doing
array[index] = 8
You were doing
array[index] = array[8]
That was causing your OutOfBounds Exception.
I tested your code and it did not sort even after having fixed the "Out Of bound Exception". I've changed your method findBig in order to make it work. The principle is :
If the length of the sub array is one (begin==end) then the biggest element is array[begin]
divide the array by half
Recusively find the index of the biggest element in the left side
Recursively find the index if the biggest element in the right side
Compare the biggest element of the left side with that of the right side of the array and return the index of the biggest of both.
This leads to the following code which sort the array in a decreasing order:
public class Sort {
public static int[] selection(int[] array) {
return sRec(array,0);
}
private static int[] sRec(int[] array, int current) {
if (current == array.length-1) { //last index of array = index we are at
return array; //it's sorted
}
else {
int indexOfBiggest = findBig(array, current,array.length-1);
int[] swapped = swap(array, indexOfBiggest, current );
return sRec(swapped, current+1);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
}
private static int findBig(int[] array, int begin, int end) {
if (begin < end) {
int middle = (begin+end)/2;
int biggestLeft = findBig(array,begin,middle);
int biggestRight = findBig(array,middle+1,end);
if(array[biggestLeft] > array[biggestRight]) {
return biggestLeft;
}else {
return biggestRight;
}
}else {
return begin;
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
// System.out.println(findBig(array,0,array.length-1));
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
}

Array index out of bounds java heap [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I know this is an amaetuer error, i understand what it means but i dont understand why i cant fix it. Ive been trying everything. Im trying to take an array of type T and switch its values around so it correctly corresponds to the rules of a heap, where the parent is always greater than the 2 children. The error is in my while loop
please dont be harsh if its something easily fixable. ive been struggling heavily and cant seem to find an answer.
public class myheap<T extends Comparable<T>> extends heap<T>
{
// constructors of the subclass should be written this way:
public myheap(int max) { super(max); }
public myheap(T[] A) {super(A);}
public void buildheap(T[] Arr){
int size = Arr.length;
int startsize = (size-1)/2;
for(int i=startsize;i>0;i--){
int l = left(i);
int r = right(i);
T temp = null;
while((Arr[r]!=null) && Arr[i].compareTo(Arr[r])<0){
if (Arr[l].compareTo(Arr[r])>0){
temp = Arr[l];
Arr[l] = Arr[i];
Arr[i] = temp;
}//if left is greater than right
else //then right must be greater than parent
temp = Arr[r];
Arr[r] = Arr[i];
Arr[i] = temp;
}//whileloop
if((Arr[r]==null) && Arr[i].compareTo(Arr[l])<0)
temp = Arr[l];
Arr[l] = Arr[i];
Arr[i] = temp;
}//for
}//buildheap
public static void main(String[] args){
String[] array = {"SH","AH","AB","YA","AY","AA","AB","LM","LL","LO"};
myheap<String> New = new myheap<String>(array.length);
for(int i=0;i<array.length;i++){
New.insert(array[i]);
}//insert
New.buildheap(array);
New.drawheap();
for(int i=0;i<array.length;i++){
System.out.println(New.deletemax() + " ");
}//for
System.out.println();
} //main
}
Heap superclass that myheap is extending
/*
Polymorphic priority heaps, largest value on top.
Heap axiom. The value at every node cannot be smaller than the values
at each of its children nodes.
Use internal array to implement heap "tree", with index 0 representing
the root. Given node index i, left(i)= 2*i+1 and right(i)=2*i+2, while
parent(i) = (i-1)/2.
*/
class heap<T extends Comparable<T>>
{
protected T[] H; // internal array representing heap.
protected int size; // size of current heap, not same as H.length!
public int size() { return size; } // size is read-only externally.
public int maxsize() { return H.length; }
public heap(T[] A) { H = A; size=0; } // preferred constructor
public heap(int m) // will cause compiler warning (ok to ignore)
{
H = (T[]) new Comparable[m]; // downcast from Object is OK.
size = 0;
}
protected int left(int i) { return 2*i+1; }
protected int right(int i) { return 2*i+2; }
protected int parent(int i) { return (i-1)/2; }
// protected is important!
// lookup heap, without delete
public T getmax()
{
if (size<1) return null;
return H[0];
}
// insert x into heap: place at end, then propagate upwards
// returns false on failure.
public boolean insert(T x)
{
if (size > H.length-1) return false;
H[size++] = x; // place at end, inc size
// propagate upwards
int cur = size-1; // current position
int p = parent(cur);
while (cur>0 && H[cur].compareTo(H[p])>0)
{ // propagate upwards
T temp = H[cur];
H[cur] = H[p]; H[p] = temp;
cur = p; // switch current to parent
p = parent(cur); // recalc parent
}//while
return true;
}//insert
// deletetop: take last element, move to top, propagate downwards:
public T deletemax()
{
if (size<0) return null;
T answer = H[0];
H[0] = H[--size]; // place at top:
// now propagate downwards.
boolean done = false;
int i = 0; // current position
int c = 0; // swap candidate
while (c != -1)
{
int l = left(i);
int r = right(i);
c = -1; // swap candidate
if (l<size && H[l].compareTo(H[i])>0) c = l; // set candidate to left
if (r<size && H[r].compareTo(H[i])>0 && H[r].compareTo(H[l])>0) c=r;
if (c!= -1)
{
T temp = H[i]; H[i] = H[c]; H[c] = temp;
i = c;
}
}//while
return answer;
}//deletemax
// but search is not log(n). Why?
public boolean search(T x)
{
for(int i=0;i<size;i++) {if (x.compareTo(H[i])==0) return true;}
return false;
}
public void drawheap() // use only with heapdisplay.java program
{
heapdisplay W = new heapdisplay(1024,768);
W.drawtree(H,size);
}
}//heap
public class heaps14
{
/**public static void main(String[] args){
heap<Integer> HI = new heap<Integer>(200);
for(int i=0;i<100;i++) HI.insert((int)(Math.random()*1000));
HI.drawheap();
for(int i=0;i<100;i++) System.out.print(HI.deletemax() + " ");
System.out.println();
}//main**/
}
You may check for null in your while loop, (Arr[r]!=null) but the problem is that you can't even get a value from the array to determine if it's null or not. You should check the index is within the range before trying to access the value from the array, using r < Arr.length or similar.
(If null) isnt the problem, arrayIndexOutofBounds means you are geting a value of an array that isnt there
Eg. Array.length =5; and you search Array[6]; - out of bounds....
The problem i think is your method right(i);
which is. i*2+2 and the array
So change the for loop to this
for(int i=startsize-2;i>0;i--)
comment if this helps.

Shifting and Re-organizing Arrays

I have an array, let's say: LRU_frame[] = {4,1,0,3}
I have a random() function that spits out a random number. If the random number n is contained in the array LRU_frame, then, n should be on LRU_frame[0] and everything else must be shifted down accordingly.
For example if random() gives me a 0, the new LRU_frame[] = {0,4,1,3}
Another example, if random() gives me a 3, the new LRU_frame[] = {3,4,1,0}
How do I do this for any Array size with any number of elements in it?
I know how to shift arrays by adding a new element on LRU_frame[0] but have no idea on how to re-organize the array like I need.
This is the code I have so far and let's assume char a is the random number(casted into char) to use and re-organize the array.
public static void LRU_shiftPageRef(char a) {
for (int i = (LRU_frame.length - 2); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
You have a good idea, you only need to find the position of the a element in the array and start the cycle from it, instead of LRU_frame.length.
int index = -1;
// find the positon of 'a' in the array
for (int i = 0; i <= (LRU_frame.length - 1); i++) {
if (LRU_frame[i] == a) {
index = i;
break;
}
}
// if it is present, do roughly the same thing as before
if (index > -1) {
for (int i = (index - 1); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
However if you can use ArrayLists it gets much easier.
// declaration
ArrayList<Integer> LRU_frame = new ArrayList<Integer>();
...
if (LRU_frame.contains(a)) {
LRU_frame.remove((Integer) a);
LRU_frame.add(0, a);
}
I think this could be the sort of thing you are after:
public static void LRU_shiftPageRef(char a) {
int index = indexOf(a);
if (index == -1) {
//not currently in array so create a new array 1 bigger than existing with a in newArray[0] or ignore depending on functionality required.
} else if (index > 0) {
//Set first entry as a and shift existing entries right
char insertChar = a;
char nextChar = LRU_frame[0];
for (int i =0; i < index; i++) {
LRU_frame[i] = insertChar;
insertChar = nextChar;
nextChar = LRU_frame[i+1];
}
LRU_frame[index] = insertChar;
} else {
//do nothing a is already at first position
}
}
public static int indexOf(char a) {
for (int i=0; i < LRU_frame.length; i++) {
if (LRU_frame[i] == a) {
return i;
}
}
return -1;
}
Use Arrays.sort(LRU_frame); to sort the entire array, or Arrays.sort(LRU_frame, fromIndex, toIndex)); to sort part of the array.
Arrays class has other useful methods like copyOfRange.

bubbleSort() for an int Array Linked List in Java

I'm having trouble with a bubbleSort method for my very unique homework assignment.
We are supposed to use a sorting method of our choice to sort, get this, a linked list of int arrays. Not an ArrayList not just a LinkedList. It works like a linked list but the each Node contains an array of a capacity of 10 ints.
I am stuck on the sorting method. I chose bubbleSort just because it was used in the last assignment and I felt most familiar with it. Any tips for a better sorting method to try would be considered helpful as well.
Here is my code:
public void bubbleSort() {
current = head; // Start at the head ArrayNode
for (int i = 0; i < size; i++) { // iterate through each ArrayNode
currentArray = current.getArray(); // get the array in this ArrayNode
int in, out;
for (out = size-1; out > 1; out--) { // outer loop (backwards)
for (in = 0; in < out; in++) { // inner loop (forwards)
if (currentArray[in] > currentArray[in+1]) // out of order?
swap(in, in+1); // swap them!
}
}
current.setArray(currentArray);
current = current.getNext();
}
}// End bubbleSort() method
// A helper method for the bubble sort
private void swap(int one, int two) {
int temp = currentArray[one];
currentArray[one] = currentArray[two];
currentArray[two] = temp;
} // End swap() method
This is a picture example of what I am supposed to be doing.
I have found a solution with selectionsort. There are a few test values, just run it to see it.
I can provide further information if needed.
import java.util.ArrayList;
import java.util.Random;
public class ArrayedListSort {
int listsize = 5; // how many nodes
int maxValue = 99; // the highest value (0 to this)
int nodeSize = 3; // size for every node
public static void main(String[] args) {
// run non static
new ArrayedListSort().runTest();
}
/**
* Log function.
*/
public void log(Object s) {
System.out.println(s);
}
public void logNoBR(Object s) {
System.out.print(s);
}
/**
* Output of list we have.
*/
public void logMyList(ArrayList<ListNode> listNode, String name) {
log("=== LOG OUTPUT " + name + " ===");
for ( int i=0; i < listNode.size(); i++) {
logNoBR(" node <" + i + ">");
logNoBR(" (");
for (int j=0; j < listNode.get(i).getSize(); j++) {
if ( j != (listNode.get(i).getSize()-1)) // if not last add ","
logNoBR( listNode.get(i).getValueAt(j) + "," );
else
logNoBR( listNode.get(i).getValueAt(j) );
}
log(")");
}
log("=====================================\n");
}
public void runTest() {
// create example List
ArrayList<ListNode> myList = new ArrayList<ListNode>();
// fill the nodes with random values
for ( int i = 0; i < listsize; i++) {
myList.add(new ListNode(nodeSize));
for (int j=0; j < nodeSize; j++) {
int randomValue = new Random().nextInt(maxValue);
myList.get(i).addValue(randomValue);
}
}
logMyList(myList, "myList unsorted"); // to see what we have
// now lets sort it
myList = sortListNode(myList);
logMyList(myList, "myList sorted"); // what we have after sorting
}
/**
* Selectionsort
*/
public ArrayList<ListNode> sortListNode(ArrayList<ListNode> myList) {
ArrayList<ListNode> retList = new ArrayList<ListNode>();
for ( int i = 0; i < listsize; i++) {
retList.add(new ListNode(nodeSize));
}
int lastSmallest = myList.get(0).getValueAt(0);
while ( !myList.isEmpty() ) {
int lastJ=0, lastI=0;
for ( int i = 0; i < myList.size(); i++) {
for (int j=0; j < myList.get(i).getSize(); j++) {
if ( myList.get(i).getValueAt(j) <= lastSmallest ) {
lastSmallest = myList.get(i).getValueAt(j);
lastJ = j;
lastI = i;
//log("Found smallest element at <"+i+","+j+"> (" + lastSmallest + ")");
}
}
}
myList.get(lastI).removeValue(lastJ);
if ( myList.get(lastI).getSize() == 0 )
myList.remove(lastI);
// add value to new list
for ( int i = 0; i < listsize; i++) {
if ( retList.get(i).getSize() < retList.get(i).getMaxSize() ) {
retList.get(i).addValue(lastSmallest);
break;
}
}
lastSmallest = Integer.MAX_VALUE;
}
return retList;
}
public class ListNode {
private ArrayList<Integer> values = new ArrayList<Integer>();
private int maxSize;
public ListNode(int maxSize) {
this.maxSize = maxSize;
}
public ArrayList<Integer> getValues() {
return values;
}
public int getMaxSize() {
return maxSize;
}
public int getSize() {
return values.size();
}
public int getValueAt(int position) {
if ( position < values.size())
return values.get(position);
else
throw new IndexOutOfBoundsException();
}
public void addValue(int value) {
values.add(value);
}
public void removeValue(int position) {
if ( position < values.size()) {
values.remove(position);
} else
throw new IndexOutOfBoundsException();
}
}
}
Here we go. The trivial solution consist in extracting all the elements of each array node and store them in a single big array, sort that big array (using Bubble Sort, Quick Sort, Shell Sort, etc.) and finally reconstruct the linked list of arrays with the the sorted values. I am almost sure that is not exactly what are you looking for.
If you want to sort the numbers in place, I can think of the following algorithm:
As others have commented, you need a comparison function that determines if a node A goes before a node B. The following algorithm use the first idea but for each pair of nodes, e.g. A->[3, 9, 7] and B->[1, 6, 8] becomes [1, 3, 6, 7, 8, 9] and finally A->[1,3, 6] and B->[7, 8, 9]. If we apply this rearrangement for each possible pair will end up with a sorted linked list of arrays (I have no proof, though).
A = head;
while (A.hasNext()) {
arrayA = A.getArray();
B = A.getNext();
while (B.hasNext()) {
arrayB = B.getArray();
// concatenate two arrays
int[] C = new int[arrayA.size() + arrayB.size()];
int i;
for (i = 0; i < arrayA.size(); i++)
C[i] = arrayA[i];
for ( ; i < arrayA.size() + arrayB.size(); i++)
C[i] = arrayB[i-arrayA.size()];
// sort the new arrays using agains Bubble sort or any
// other method, or Arrays.sort()
Arrays.sort(C);
// now return the sorted values to the two arrays
for (i = 0; i < arrayA.size(); i++)
arrayA[i] = C[i];
for (i = 0; i < arrayB.size(); i++)
arrayB[i] = C[i+arrayA.size()];
}
}
This is kind of pseudo code because I haven't worked with linked lists in Java but I think you get the idea.
NOTE: I haven't tested the code, it may contain horrors.

Implementing a binary insertion sort using binary search in Java

I'm having trouble combining these two algorithms together. I've been asked to modify Binary Search to return the index that an element should be inserted into an array. I've been then asked to implement a Binary Insertion Sort that uses my Binary Search to sort an array of randomly generated ints.
My Binary Search works the way it's supposed to, returning the correct index whenever I test it alone. I wrote out Binary Insertion Sort to get a feel for how it works, and got that to work as well. As soon as I combine the two together, it breaks. I know I'm implementing them incorrectly together, but I'm not sure where my problem lays.
Here's what I've got:
public class Assignment3
{
public static void main(String[] args)
{
int[] binary = { 1, 7, 4, 9, 10, 2, 6, 12, 3, 8, 5 };
ModifiedBinaryInsertionSort(binary);
}
static int ModifiedBinarySearch(int[] theArray, int theElement)
{
int leftIndex = 0;
int rightIndex = theArray.length - 1;
int middleIndex = 0;
while(leftIndex <= rightIndex)
{
middleIndex = (leftIndex + rightIndex) / 2;
if (theElement == theArray[middleIndex])
return middleIndex;
else if (theElement < theArray[middleIndex])
rightIndex = middleIndex - 1;
else
leftIndex = middleIndex + 1;
}
return middleIndex - 1;
}
static void ModifiedBinaryInsertionSort(int[] theArray)
{
int i = 0;
int[] returnArray = new int[theArray.length + 1];
for(i = 0; i < theArray.length; i++)
{
returnArray[ModifiedBinarySearch(theArray, theArray[i])] = theArray[i];
}
for(i = 0; i < theArray.length; i++)
{
System.out.print(returnArray[i] + " ");
}
}
}
The return value I get for this when I run it is 1 0 0 0 0 2 0 0 3 5 12. Any suggestions?
UPDATE: updated ModifiedBinaryInsertionSort
static void ModifiedBinaryInsertionSort(int[] theArray)
{
int index = 0;
int element = 0;
int[] returnArray = new int[theArray.length];
for (int i = 1; i < theArray.lenght - 1; i++)
{
element = theArray[i];
index = ModifiedBinarySearch(theArray, 0, i, element);
returnArray[i] = element;
while (index >= 0 && theArray[index] > element)
{
theArray[index + 1] = theArray[index];
index = index - 1;
}
returnArray[index + 1] = element;
}
}
Here is my method to sort an array of integers using binary search.
It modifies the array that is passed as argument.
public static void binaryInsertionSort(int[] a) {
if (a.length < 2)
return;
for (int i = 1; i < a.length; i++) {
int lowIndex = 0;
int highIndex = i;
int b = a[i];
//while loop for binary search
while(lowIndex < highIndex) {
int middle = lowIndex + (highIndex - lowIndex)/2; //avoid int overflow
if (b >= a[middle]) {
lowIndex = middle+1;
}
else {
highIndex = middle;
}
}
//replace elements of array
System.arraycopy(a, lowIndex, a, lowIndex+1, i-lowIndex);
a[lowIndex] = b;
}
}
How an insertion sort works is, it creates a new empty array B and, for each element in the unsorted array A, it binary searches into the section of B that has been built so far (From left to right), shifts all elements to the right of the location in B it choose one right and inserts the element in. So you are building up an at-all-times sorted array in B until it is the full size of B and contains everything in A.
Two things:
One, the binary search should be able to take an int startOfArray and an int endOfArray, and it will only binary search between those two points. This allows you to make it consider only the part of array B that is actually the sorted array.
Two, before inserting, you must move all elements one to the right before inserting into the gap you've made.
I realize this is old, but the answer to the question is that, perhaps a little unintuitively, "Middleindex - 1" will not be your insertion index in all cases.
If you run through a few cases on paper the problem should become apparent.
I have an extension method that solves this problem. To apply it to your situation, you would iterate through the existing list, inserting into an empty starting list.
public static void BinaryInsert<TItem, TKey>(this IList<TItem> list, TItem item, Func<TItem, TKey> sortfFunc)
where TKey : IComparable
{
if (list == null)
throw new ArgumentNullException("list");
int min = 0;
int max = list.Count - 1;
int index = 0;
TKey insertKey = sortfFunc(item);
while (min <= max)
{
index = (max + min) >> 1;
TItem value = list[index];
TKey compKey = sortfFunc(value);
int result = compKey.CompareTo(insertKey);
if (result == 0)
break;
if (result > 0)
max = index - 1;
else
min = index + 1;
}
if (index <= 0)
index = 0;
else if (index >= list.Count)
index = list.Count;
else
if (sortfFunc(list[index]).CompareTo(insertKey) < 0)
++index;
list.Insert(index, item);
}
Dude, I think you have some serious problem with your code. Unfortunately, you are missing the fruit (logic) of this algorithm. Your divine goal here is to get the index first, insertion is a cake walk, but index needs some sweat. Please don't see this algorithm unless you gave your best and desperate for it. Never give up, you already know the logic, your goal is to find it in you. Please let me know for any mistakes, discrepancies etc. Happy coding!!
public class Insertion {
private int[] a;
int n;
int c;
public Insertion()
{
a = new int[10];
n=0;
}
int find(int key)
{
int lowerbound = 0;
int upperbound = n-1;
while(true)
{
c = (lowerbound + upperbound)/2;
if(n==0)
return 0;
if(lowerbound>=upperbound)
{
if(a[c]<key)
return c++;
else
return c;
}
if(a[c]>key && a[c-1]<key)
return c;
else if (a[c]<key && a[c+1]>key)
return c++;
else
{
if(a[c]>key)
upperbound = c-1;
else
lowerbound = c+1;
}
}
}
void insert(int key)
{
find(key);
for(int k=n;k>c;k--)
{
a[k]=a[k-1];
}
a[c]=key;
n++;
}
void display()
{
for(int i=0;i<10;i++)
{
System.out.println(a[i]);
}
}
public static void main(String[] args)
{
Insertion i=new Insertion();
i.insert(56);
i.insert(1);
i.insert(78);
i.insert(3);
i.insert(4);
i.insert(200);
i.insert(6);
i.insert(7);
i.insert(1000);
i.insert(9);
i.display();
}
}

Categories

Resources