I'm really new to java and slowly learning so not sure if there is an obvious way to do this but I basically have two lists that I want to merge together to form a single list.
The python code for this, uses a function called zip. Say I have list1 = 1,2,3,4,5 and list2= 6,7,8,9,10..Then I want to make a new list with something like new_list = (1,6), (2,7), (3,8), (4,9), (5,10).
I found a question that had a similar problem but I don't want to use an external library and would rather learn how to create this function myself.
The generalized algorithm would look something like this (assuming you want to take N input lists):
public <T> List<List<T>> zip(List<T> ... lists) {
if(lists.isEmpty()) {
return Collections.<List<T>>emptyList();
}
// validate that the input lists are all the same size.
int numItems = lists[0].size();
for(int i = 1; i < lists.length; i++) {
if(lists[i].size() != numItems) {
throw new IllegalArgumentException("non-uniform-length list at index " + i);
}
}
List<List<T>> result = new ArrayList<List<T>>();
for(int i = 0; i < numItems; i++) {
// create a tuple of the i-th entries of each list
List<T> tuple = new ArrayList<T>(lists.length);
for(List<T> list : lists) {
tuple.add(list.get(i));
}
// add the tuple to the result
result.add(tuple);
}
return result;
}
public class Blammy
{
private String left;
private String right;
public Blammy(final String left, final String right)
{
this.left = left;
this.right = right;
}
public String toString()
{
return "(" + left + ", " + right + ")";
}
}
public class Kramlish
{
public List<Blammy> mergalish(final List<String> left, final List<String> right)
{
int leftSize;
int maxSize;
int rightSize;
String leftValue;
List<Blammy> returnValue;
String rightValue;
if (left != null)
{
leftSize = left.size();
}
else
{
leftSize = 0;
}
if (right != null)
{
rightSize = right.size();
}
else
{
rightSize = 0;
}
if (leftSize > rightSize)
{
maxSize = leftSize;
}
else
{
maxSize = rightSize;
}
if (maxSize > 0)
{
returnValue = new ArrayList<Blammy>(maxSize);
for (int index = 0; index < maxSize; ++index)
{
if (index < leftSize)
{
leftValue = left.get(index);
}
else
{
leftValue = null;
}
if (index < rightSize)
{
rightValue = right.get(index);
}
else
{
rightValue = null;
}
Blammy item = new Blammy(leftValue, rightValue);
returnValue.add(item);
}
}
else
{
returnValue = new ArrayList<Blammy>();
}
return returnValue;
}
}
Related
I have Implemented B-Tree, I have given toString to Implement method in Node class as it but its giving errot in this line children.forEach(c ->builder.append(c.toString(depth + 1))); I have tried various methods but not worked
here is other B-Tree files and pdf where is given toString Methods and other Instruction check out these files
toString code
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Node<E extends Comparable<E>> {
public int nodeLocation;
public int index;
private E[] keys = null;
int keysSize = 0;
public Node<E>[] children = null;
public Node<E>[] elements;
int childrenSize = 0;
private Comparator<Node<E>> comparator = new Comparator<Node<E>>() {
#Override
public int compare(Node<E> arg0, Node<E> arg1) {
return arg0.getKey(0).compareTo(arg1.getKey(0));
}
};
protected Node<E> parent = null;
Node(Node<E> parent, int maxKeySize, int maxChildrenSize) {
this.parent = parent;
this.keys = (E[]) new Comparable[maxKeySize + 1];
this.keysSize = 0;
this.children = new Node[maxChildrenSize + 1];
this.childrenSize = 0;
}
E getKey(int index) {
return keys[index];
}
int indexOf(E value) {
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value))
return i;
}
return -1;
}
void addKey(E value) {
keys[keysSize++] = value;
Arrays.sort(keys, 0, keysSize);
}
E removeKey(E value) {
E removed = null;
boolean found = false;
if (keysSize == 0)
return null;
for (int i = 0; i < keysSize; i++) {
if (keys[i].equals(value)) {
found = true;
removed = keys[i];
} else if (found) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
}
if (found) {
keysSize--;
keys[keysSize] = null;
}
return removed;
}
E removeKey(int index) {
if (index >= keysSize)
return null;
E value = keys[index];
for (int i = index + 1; i < keysSize; i++) {
// shift the rest of the keys down
keys[i - 1] = keys[i];
}
keysSize--;
keys[keysSize] = null;
return value;
}
int numberOfKeys() {
return keysSize;
}
Node<E> getChild(int index) {
if (index >= childrenSize)
return null;
return children[index];
}
int indexOf(Node<E> child) {
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child))
return i;
}
return -1;
}
boolean addChild(Node<E> child) {
child.parent = this;
children[childrenSize++] = child;
Arrays.sort(children, 0, childrenSize, comparator);
return true;
}
boolean removeChild(Node<E> child) {
boolean found = false;
if (childrenSize == 0)
return found;
for (int i = 0; i < childrenSize; i++) {
if (children[i].equals(child)) {
found = true;
} else if (found) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
}
if (found) {
childrenSize--;
children[childrenSize] = null;
}
return found;
}
Node<E> removeChild(int index) {
if (index >= childrenSize)
return null;
Node<E> value = children[index];
children[index] = null;
for (int i = index + 1; i < childrenSize; i++) {
// shift the rest of the keys down
children[i - 1] = children[i];
}
childrenSize--;
children[childrenSize] = null;
return value;
}
int numberOfChildren() {
return childrenSize;
}
/**
* {#inheritDoc}
*/
public String toStringg() {
return toString(0);
}
// // based on what toString() does, think about what ‘elements’ and ‘children’
// can be
private String toString(int depth) {
StringBuilder builder = new StringBuilder();
String blankPrefix = new String(new char[depth]).replace("\0", "\t");
List<String> printedElements = new LinkedList<>();
for (Node<E> e : elements)
printedElements.add(e.toString());
String eString = String.join(" :: ", printedElements);
builder.append(blankPrefix).append(eString).append("\n");
children.forEach(c -> builder.append(c.toString(depth + 1))); // this line is giving error
return builder.toString();
}
}
I Have Gievn pdf File where is gievn insructions and code implement I have tried to change childern but not worked I am bound to not make changes in gievn toString method
Arrays in Java doesn't declare their own behavior (don't try to reproduce your experience from languages like JavaScript and TypeScript, where Arrays have methods).
Therefore, you can't invoke method forEach() on the children array (this method is accessible with implementations of Iterable interface, like Collections).
You can use an enhanced for-loop instead:
for (Node<E> node : children) {
builder.append(node.toString(depth + 1));
}
Alternatively, if you declare the property children as a List you'll be able use forEach() with it:
public List<Node<E>> children;
Judging by your assignment requirements, that what you're expected to do.
That would require changing all the methods that make use of children because you can't dial with a List in the same way as with an array. I.e. you would need to use the behavior of the List interface.
children[i] would turn to children.get(i). And children[i] = ... would become children.set(i, ...), or children.add(...).
I am trying to create a simple pagination routine for values held in an ArrayList. Basically what I want to do is render the first five elements in the ArrayList at first go. And then when users click on Next (increment by another 5) and Previous (decrease by 5).
My logic looks like this:
class foo
{
private static final int defaultStep = 5;
private int moveCounter;
private List<String> values;
public foo()
{
values = new ArrayList<String>();
values.add("Fiber Channel");
values.add("Copper Channel");
...
}
private void pageNext()
{
if (moveCounter > -1 && moveCounter < values.size())
{
int currentIndex = (moveCounter + 1);
renderValues(currentIndex, false);
}
}
private void pagePrevious()
{
if (moveCounter > -1 && moveCounter <= values.size())
{
renderValues(moveCounter-1, true);
}
}
private void renderValues(int startIndex, boolean isPreviousCall)
{
if (startIndex > -1)
{
StringBuilder html = new StringBuilder();
List<String> valuesToRender = new ArrayList<String>();
int checkSteps = 1;
while (startIndex < values.size())
{
valuesToRender.add(values.get(startIndex));
if (checkSteps == defaultStep) break;
startIndex++;
checkSteps++;
}
moveCounter = startIndex;
//TODO: Build html String
...
}
}
}
I have an issue with pagePrevious call, can you guys help me build the valuesToRender 5-steps up values array before adding the value to render to the valuesToRender array.
I tried doing something like this also:
for (int start = startIndex, end = values.size() - 1; start < end; start++, end--)
{
if (isPreviousCall) valuesToRender.add(values.get(end));
else valuesToRender.add(values.get(start));
if (checkSteps == defaultStep) break;
checkSteps++;
}
But this doesn't seems to work neither. Can you guys spot and help me fix this issue.
Thanks Guys.
Based on "pscuderi" solution here
I've built a wrapping class that can be helpful for someone looking for this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PaginatedList<T> {
private static final int DEFAULT_PAGE_SIZE = 10;
private List<T> list;
private List<List<T>> listOfPages;
private int pageSize = DEFAULT_PAGE_SIZE;
private int currentPage = 0;
public PaginatedList(List<T> list) {
this.list = list;
initPages();
}
public PaginatedList(List<T> list, int pageSize) {
this.list = list;
this.pageSize = pageSize;
initPages();
}
public List<T> getPage(int pageNumber) {
if (listOfPages == null ||
pageNumber > listOfPages.size() ||
pageNumber < 1) {
return Collections.emptyList();
}
currentPage = pageNumber;
List<T> page = listOfPages.get(--pageNumber);
return page;
}
public int numberOfPages() {
if (listOfPages == null) {
return 0;
}
return listOfPages.size();
}
public List<T> nextPage() {
List<T> page = getPage(++currentPage);
return page;
}
public List<T> previousPage() {
List<T> page = getPage(--currentPage);
return page;
}
public void initPages() {
if (list == null || listOfPages != null) {
return;
}
if (pageSize <= 0 || pageSize > list.size()) {
pageSize = list.size();
}
int numOfPages = (int) Math.ceil((double) list.size() / (double) pageSize);
listOfPages = new ArrayList<List<T>>(numOfPages);
for (int pageNum = 0; pageNum < numOfPages;) {
int from = pageNum * pageSize;
int to = Math.min(++pageNum * pageSize, list.size());
listOfPages.add(list.subList(from, to));
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 62; i++) {
list.add(i);
}
PaginatedList<Integer> paginatedList = new PaginatedList<Integer>(list);
while (true) {
List<Integer> page = paginatedList.nextPage();
if (page == null || page.isEmpty()) {
break;
}
for (Integer value : page) {
System.out.println(value);
}
System.out.println("------------");
}
}
}
Change
if (moveCounter > -1 && moveCounter <= archive.size())
{
renderValues(moveCounter-1, true);
}
to
if (moveCounter > 0 && moveCounter <= archive.size())
{
renderValues(moveCounter-1, true);
}
I would do it like this:
I'm not sure what renderValues does, and whether we have to substract 1 or maybe defaultStep from the upper bound of the moveCounter.
private void pageMove (int step)
{
moveCounter = moveCounter + step;
if (moveCounter < 0) moveCounter = 0;
if (moveCounter > values.size ()) moveCounter = values.size ();
renderValues (currentIndex, false);
}
private void pageNext ()
{
pageMove (defaultStep);
}
private void pagePrevious ()
{
pageMove (-defaultStep);
}
The first 3 lines could be packed into two big ternary experssions like so:
mc = ((mc + s) < 0) ? 0 : ((mc + s) > vs) ? vs : (mc + s);
but the 3 lines solution is better to follow.
Here is a simple java function for pagination. Note that the page starts from 0 (first page)
public List<Object> pagedResponse(List<Object> allItems, int page, int limit){
int totalItems = allItems.size();
int fromIndex = page*limit;
int toIndex = fromIndex+limit;
if(fromIndex <= totalItems) {
if(toIndex > totalItems){
toIndex = totalItems;
}
return allItems.subList(fromIndex, toIndex);
}else {
return Collections.emptyList();
}
}
Recently I took part in a java coding challenge in my college and was asked this problem which I found difficult to implement.
Problem was to implement a method detect that given two LinkedList, return the index where second list is sublist of first.
detect((1,2,3),(2,3)) should return 1
The node structure to the list was
LinkedListNode {
String val;
LinkedListNode *next;
}
and the method signature
static int detect(LinkedListNode list, LinkedListNode sublist)
What would be the basic algorithm to approach this problem. I am a newbie to data structures.
I believe Collections.indexOfSubList implements this. You can look at it's implementation.
Basically:
ListIterator<?> si = source.listIterator();
nextCand:
for (int candidate = 0; candidate <= maxCandidate; candidate++) {
ListIterator<?> ti = target.listIterator();
for (int i=0; i<targetSize; i++) {
if (!eq(ti.next(), si.next())) {
// Back up source iterator to next candidate
for (int j=0; j<i; j++)
si.previous();
continue nextCand;
}
}
return candidate;
}
The basic idea is to traverse the second list and for every index in this list check for equality in first list for consecutive elements. The following algorithm will work for you:
public static void main(String[] args) {
List<Integer> list1 = new LinkedList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(6);
List<Integer> list2 = new LinkedList<Integer>();
list2.add(2);
list2.add(3);
boolean contains = true;
int currIndex = 0;
int i = 0,j = 0;
for(;j<list2.size();j++) {
int e2 = list2.get(j);
for(i=currIndex;i<list1.size();i++) {
if(e2 == list1.get(i)) {
break;
}
}
if(i == list1.size()) {
contains = false;
break;
}
currIndex++;
if( contains && (currIndex == list2.size()) ) {
System.out.println("Index is: " + (i-j));
}
}
}
This prints Index is: 1 as expected.
static int detect(LinkedListNode list, LinkedListNode sublist) {
int counter = 0;
int index = -1;
LinkedListNode sub = sublist;
do {
if (list.val == sub.val) {
if (index == -1)
index = counter;
if (sub.next != null) {
sub = sub.next;
if (sub.next == null) {
return index;
}
}
} else {
index = -1;
sub = sublist;
}
list = list.next;
counter++;
} while (list.next != null);
return index;
}
Since, the value is String here :-
static int find(LinkedListNode list, LinkedListNode sublist) {
String listString = convertLinkedListToString(list);
String sublistString = convertLinkedListToString(sublist);
return listString.indexOf(sublistString);
}
private static String convertLinkedListToString(LinkedListNode list) {
String listAsString = "";
while(list != null) {
listAsString = listAsString + list.val;
list = list.next;
}
return listAsString;
}
I want to convert a string input like 2,3,6,7,8,10,12,14,15,16 to 2-3,6-8,10,12,14-16 using java
I tried using the below code
Vector ar=new Vector();
int lastadded=0;
String ht="";
String [] strarray=str.split(",");
strarray=sortArray(strarray);
Vector intarray=new Vector();
for(int i=0;i<strarray.length;i++)
{
int temp=1;
for(int j=1;j<=intarray.size();j++)
{
if(Integer.parseInt(strarray[i])==Integer.parseInt(intarray.get(j-1).toString()))
{
temp=0;
}
}
if(temp==1)
{
intarray.add(Integer.parseInt(strarray[i]));
ar.add(Integer.parseInt(strarray[i]));
}
}
ht="";
String strdemo="";
for(int i=0;i<intarray.size();i++)
{
if(ht=="")
{
ht=ar.get(i)+"";
lastadded=i;
}
else
{
strdemo=(String)ht;
if(strdemo.length()==ar.get(0).toString().length())
{
if(Integer.parseInt(strdemo.substring(0))==Integer.parseInt(ar.get(i).toString())-1)
{
strdemo=strdemo+"-"+ar.get(i);
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+ar.get(i);
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}
else if(strdemo.length()==3)
{
strdemo=(String)ht;
if(Integer.parseInt(strdemo.substring(strdemo.length()-1,strdemo.length()))==Integer.parseInt(ar.get(i).toString())-1)
{
strdemo=strdemo.substring(0,strdemo.length()-2)+"-"+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}//Else IF
else{
strdemo=(String)ht;
int de=1;
int ddd=lastadded;
if(ddd==Integer.parseInt(ar.get(i).toString())-1)
{
int lastaddedlen=(lastadded+"").length();
String symbol=strdemo.substring(strdemo.length()-lastaddedlen-1,strdemo.length()-lastaddedlen);
if(symbol.equalsIgnoreCase("-"))
strdemo=strdemo.substring(0,strdemo.length()-lastaddedlen-1)+"-"+Integer.parseInt(ar.get(i).toString());
else
strdemo=strdemo+"-"+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
else
{
strdemo=strdemo+","+Integer.parseInt(ar.get(i).toString());
lastadded=Integer.parseInt(ar.get(i).toString());
ht=strdemo;
}
}
}
}
Here sortArray function sorts the array descending and returns
protected static String[] sortArray(String ss[])
{
String temp;
for(int i=0;i<ss.length;i++)
{
for(int j=0;j<ss.length;j++)
{
if(Integer.parseInt(ss[i])<Integer.parseInt(ss[j]))
{
temp=ss[i];
ss[i]=ss[j];
ss[j]=temp;
}
}
}
return ss;
}
I am not getting consistant results for some inputs for example for the below case
2,3,6,7,8,10,12,14,15,16 it gives 2-3,6-8,10,12,14-16 (which is correct)
while for 2,4,5,6,7,8,10,12,14,15,16 it gives 2-8,10,12,14-16 (which actually should have been 2,4-8,10,12,14-16)
Where does the code go inconsistent is what I need to find out..
This is pretty ugly and verbose in Java, but here is a version. Note, it uses StringUtils from Spring at the very end for the trivial but also ugly process of converting a String collection to a comma delimited string.
The key is to use a separate class to model the numeric ranges. Let this class know how to turn itself into a String. Then you won't have so much logic around appending to a StringBuilder.
Also, try to think in terms of collections. This always makes things clearer. The pseudo-code is something like: String becomes List<Integer> becomes List<Range> and finally becomes String.
public class Ranges {
// A class that models a range of integers
public static class Range {
private int low;
private int high;
public Range(int low, int high) {
this.low = low;
this.high = high;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
#Override
public String toString() {
return (low == high) ? String.valueOf(low) : String.format("%d-%d", low, high);
}
}
public static void main(String[] args) {
String input = "2,3,6,7,8,10,12,14,15,16";
// Turn input string into a sorted list of integers
List<Integer> inputNumbers = new ArrayList<Integer>();
for (String num : input.split(",")) {
inputNumbers.add(Integer.parseInt(num));
}
Collections.sort(inputNumbers);
// Flatten list of integers into a (shorter) list of Ranges
Range thisRange = null; // the current range being built
List<Range> ranges = new ArrayList<Range>();
for (Integer number : inputNumbers) {
if (thisRange != null && number <= thisRange.getHigh() + 1) {
// if we are already building a range (not null) && this new number is
// the old high end of the range + 1, change the high number.
thisRange.setHigh(number);
} else {
// create a new range and add it to the list being built
thisRange = new Range(number, number);
ranges.add(thisRange);
}
}
// Join List<String> into a single String
String result = StringUtils.collectionToCommaDelimitedString(ranges);
System.out.println("result = " + result);
}
}
Here is my implementation. Hope this help.
You have to pass these values
e.g int[] a = {2,3,4,5,6,7,8,10,12, 14,15,16,18,19,21,22,26};
to the following method.
public List<String> listIntRange(int[] values)
{
List<String> intRangeList = new ArrayList<String>();
int first = 0;
int current = 0;
int prev = 0;
int count = 0;
if (values == null || values.length < 1)
return intRangeList;
first = prev = values[0];
int index = 1;
boolean range = false;
for(index = 1; index < values.length; index++)
{
current = values[index];
if(current - prev == 1)
{
range = true;
prev = current;
continue;
}
if(range == true)
{
intRangeList.add(first + "-" + prev);
}
else
{
intRangeList.add("" + first);
}
first = current;
prev = current;
range = false;
}
if(range == true)
{
intRangeList.add(first + "-" + current);
}
else
{
intRangeList.add("" + current);
}
return intRangeList;
}
Output is as follows, when print out the values from intRangeList:
2-8,10,12,14-16,18-19,21-22,26,
Please ignore last comma ','.
There seems to be a problem in add method of the class I have written.. I want to make a SortedList using an array, but I can't figure out what the problem is. This is my code:
public class SortedList {
private Integer[] elements;
private int size;
private int capacity;
public SortedList(int cap) {
elements = new Integer[cap];
if (cap > 0)
{
cap = capacity;
}
else
capacity = 10;
}
public boolean isEmpty()
{
return size == 0;
}
public boolean isFull()
{
return size == capacity;
}
public int size()
{
return size;
}
public void doubleCapacity()
{
capacity = capacity * 2;
}
public void add(Integer el)
{
if(this.isEmpty())
{
elements[0] = el;
size++;
}
else if(this.isFull())
{
this.doubleCapacity();
for(int i = 0; i<this.size(); i++)
{
if(el >= elements[i])
{
elements[i+2] = elements[i+1];
elements[i+1] = el;
}
else
{
elements[i+1] = elements[i];
elements[i] = el;
}
}
size++;
}
else
{
for(int i = 0; i<this.size(); i++)
{
if(el >= elements[i])
{
elements[i+2] = elements[i+1];
elements[i+1] = el;
}
else
{
elements[i+1] = elements[i];
elements[i] = el;
}
}
size++;
}
}
public String toString()
{
String s = "";
s = s + "<SortedList[";
for(int i = 0; i < this.size(); i++)
{
s = s + elements[i];
if(i < this.size()-1)
s = s + ",";
}
s = s + "]>";
return s;
}
public static void main(String[] args)
{
SortedList sl = new SortedList(5);
sl.add(3);
//sl.add(2);
sl.add(4);
sl.add(5);
// sl.add(6);
System.out.println(sl.toString());
}
}
My code works if I only add 2 Integers to my list, but when I try to add the numbers 3,4,5 then I get 3,5,5...
What can be the problem? Thanks..
public class SortedList {
private Integer[] elements;
private int size=0;
private int capacity;
public SortedList(int cap) {
elements = new Integer[cap];
if (cap > 0)
{
capacity = cap;
}
else
capacity = 10;
}
public boolean isEmpty()
{
return size == 0;
}
public boolean isFull()
{
return size == capacity;
}
public int size()
{
return size;
}
public void doubleCapacity()
{
capacity = capacity * 2;
}
public void add(Integer el) throws Exception{
elements[size] = el;
size++;
if(size>capacity){
throw new Exception("Size Exceeded");
}
}
public String toString()
{
sort();
String s = "";
s = s + "<SortedList[";
for(int i = 0; i < this.size(); i++)
{
s = s + elements[i];
if(i < this.size()-1)
s = s + ",";
}
s = s + "]>";
return s;
}
public void sort(){
for (int i=0; i <size()-1; i++) {
if (elements[i] > elements[i+1]) {
// exchange elements
int temp = elements[i];
elements[i] = elements[i+1];
elements[i+1] = temp;
}
}
}
public static void main(String[] args)
{
try {
SortedList sl = new SortedList(5);
sl.add(3);
//sl.add(2);
sl.add(6);
sl.add(5);
// sl.add(6);
System.out.println(sl.toString());
} catch (Exception ex) {
Logger.getLogger(SortedList.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Your insertion code doesn't work.
elements[i+1] = elements[i];
elements[i] = el;
What happens to the old value of elements[i+1]?
I'd recommend the following changes to the previous solution. If you're only calling sort in toString(), your list is going to get out of order quickly in cases where you have multiple unsorted elements in a row (Now you could remove sort() from toString()). It's essentially a quick insertion sort that dies as soon as it can't make any more swaps down the list. Again, as dty suggested, a faster choice would be a binary search to find the insertion point.
public void doubleCapacity(){
capacity = capacity * 2;
Integer temp[] = new Integer[capacity];
for (int i = 0; i < size; i++){
temp[i] = elements[i];
}
elements = temp;
}
public void add(Integer el){
if(size+1>capacity){
doubleCapacity();
}
elements[size] = el;
size++;
sort();
}
public void sort(){
//Iterates down the list until it's sorted.
for (int i=size()-2; i >= 0 && (elements[i] < elements[i+1]); i--) {
// exchange elements
int temp = elements[i];
elements[i] = elements[i+1];
elements[i+1] = temp;
}
}