java - Inserts an element into an array and returning the index reallocating the array in case of full array -
i need implement method public int insert (int x) inserts x in "elements" array keeping ordered, , returns index entered; if element present, don't insert x , returns -1; if array full, reallocates "elements" array in array of double size , insert item x. know there similar methods in api rather implement it.
i wrote this, not know how complete it...
public int insert(int x) { if(numelements == elements.length) { //code } int pos = binarysearch(x); if(pos != -1) return -1; if(elements[-(pos + 1)] != null) { for(int = numelements; >= -(pos + 1); i--) elements[i + 1] = elements[i]; } elements[-(pos + 1)] = x; numelements++; return -(pos + 1); }
i not know if wrote correct, however, , miss case of full array. can me? thanks
private int binarysearch(int x) { int inf = 0; int sup = numelements - 1; if(sup == -1 || elements[0] > x) return -1; if(elements[sup] < x) return -(numelements + 1); //invariante di ciclo: se x in a, allora x in a[inf...sup] while(inf <= sup) { int = (inf + sup) >>> 1; //divide per due if(elements[i] > x) sup = - 1; else if(elements[i] < x) inf = + 1; else return i; } return -(inf + 1); }
here go.
what did create new array twice size , use system.arraycopy
move existing elements. lastly assigned reference of enlarged array elements
variable.
i used system.arraycopy
because faster manually made loop-copy. using native implementation jvm.
also replaced check array displacement , loop system.arraycopy
. also, -(pos + 1) gives negative number.
public int insert(int x) { if(numelements == elements.length) { int[] enlargedelements = new int[elements.length * 2]; system.arraycopy(elements, 0, enlargedelements, 0, elements.length); elements = enlargedelements; } int pos = binarysearch(x); if(pos == -1) return -1; if(pos < numelements) { system.arraycopy(elements, pos, elements, pos + 1, numelements - pos); } elements[pos] = x; numelements++; return pos; } private int binarysearch(int x) { int inf = 0; int sup = numelements - 1; if(sup == -1 || elements[0] > x) return 0; if(elements[sup] < x) return numelements; //invariante di ciclo: se x in a, allora x in a[inf...sup] while(inf <= sup) { int = (inf + sup) >>> 1; //divide per due if(elements[i] > x) sup = - 1; else if(elements[i] < x) inf = + 1; else return -1; } return inf; }
Comments
Post a Comment