java - Reversing a Generic Array using "in situ" -
for generic array added method reverse() has reverse array without using additional array of elements , trying perform reverse “in situ” using swap operations. may have gotten wrong , if how can reversed “in situ” using swap operations?
import java.util.collections; class genericarray<e> { private e[] array; private int size; public genericarray() { array = (e[]) new object[10]; size = 0; } public e get(int i) { return array[i]; } public void set(int i, e value) { if (i < size) array[i] = value; } public void add(e value) { array[size++] = value; } public boolean isfull() { return size == array.length; } public void remove(int i) { (int j = i; j < size; j++) array[j] = array[j + 1]; size--; } public void insert(int i, e value) { (int j = size; j >= i; j--) array[j + 1] = array[j]; array[i] = value; size++; } public void display() { (int = 0; < size; i++) system.out.print(array[i] + " "); system.out.println(); } public e reverse() { collections.reverse(array); } }
if mean want manually without using collections.reverse (that code shouldn't compile btw, reverse needs list parameter), traverse array beginning middle swapping elements @ opposite sides of range:
public e[] reverse() { (int = 0; < size/2; i++){ e tmp=array[i]; array[i] = array[size - - 1]; array[size - - 1]=tmp; } return array; // if want return } more info on in situ algorithms on wikipedia.
regarding add implementation ensures there enough space:
public void add(e value) { int newsize=size+1; if(newsize<size){ //the array big enough, add element array[newsize]=value; }else{ //the array small, create new 1 //the old content twice bigger , add //the new element array=arrays.copyof(array,size*2); array[newsize]=value; } size=newsize; }
Comments
Post a Comment