Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- *
- * @author Timothy
- */
- public class SortedArray {
- public int size;
- public int increment;
- public int top;
- Comparable[] a = new Comparable [size];
- public SortedArray(int initialSize, int incrementAmount)
- {
- top = -1;
- size = initialSize;
- increment = incrementAmount;
- }
- public int appropriatePosition(Comparable value)
- {
- int hold = 0;
- if(top == -1)
- {
- return 0;
- }
- else
- {
- for(int i = 0; i <= top; i++)
- {
- if(a[i].compareTo(value) > 0)
- {
- hold = i;
- break;
- }
- }
- }
- return hold;
- }
- public Comparable smallest()
- {
- int min = 0;
- for(int i = 0; i < top; i++)
- {
- if( a[i].compareTo(a[i + 1]) <= 0)
- {
- min = i;
- }
- }
- return a[min];
- }
- public Comparable largest()
- {
- int max = 0;
- for(int i = 0; i < top; i++)
- {
- if( a[i].compareTo(a[i + 1]) >= 0)
- {
- max = i;
- }
- }
- return a[max];
- }
- public void insert(Comparable value)
- {
- //Shifting numbers to the top
- if(full() == true)
- {
- Comparable[] tempArray = new Comparable[top + increment];
- for(int i= 0; i< size; i++)
- {
- tempArray[i]= a[i];
- a = tempArray;
- }
- size = top + increment;
- }
- if(a[appropriatePosition(value) + 1] != null)
- {
- for(int i = top; i < appropriatePosition(value); i--)
- {
- a[i + 1] = a[i];
- }
- }
- a[appropriatePosition(value) + 1]= value;
- }
- public int find(Comparable f)
- {
- for(int i = 0; i < top; i++)
- {
- if(a[i] == f)
- {
- return i;
- }
- }
- return -1;
- }
- public void delete(Comparable d)
- {
- if(top > -1)
- {
- a[find(d)] = a[find(d) + 1];
- for(int i = find(d); i < size; i++)
- {
- a[i] = a[i+1];
- }
- top--;
- Comparable[] tempArray = new Comparable[top];
- for(int i= 0; i< size; i++)
- {
- tempArray[i]= a[i];
- a = tempArray;
- }
- size = top - 1;
- }
- else
- {
- System.out.println("Array is already empty.");
- }
- }
- public void print()
- {
- for(int i = 0; i < size; i++)
- {
- System.out.println(a[i]);
- }
- }
- public void clear()
- {
- for(int i = 0; i < size; i++)
- {
- a[i] = null;
- }
- }
- public boolean full()
- {
- for(int i = 0; i <= size; i++)
- {
- if(a[i] != null)
- {
- return true;
- }
- }
- return false;
- }
- public boolean empty()
- {
- for(int i = 0; i < size; i++)
- {
- if(a[i] != null)
- {
- return false;
- }
- }
- return true;
- }
- public int compareTo(Object obj)
- {
- Comparable x = (Comparable) obj;
- if(this.compareTo(obj) > 0)
- {
- return 1;
- }
- else if(this.compareTo(obj) == 0)
- {
- return 0;
- }
- else if(this.compareTo(obj) < 0)
- {
- return -1;
- }
- return 0;
- }
- }
Add Comment
Please, Sign In to add comment