Reputation: 47
so what I am trying to do is convert some methods in my Array class from regular Arrays into ArrayLists. However, I have run into two distinct issues. Firstly, while reversing the order of my ArrayList, I have noticed that oddly it prints out say, if I have 6 integers, and I am trying to reverse, it will print out the index locations of the first 3 and the actual integers of the last 3. For example it will print out: reverse order: 5, 4, 3, 96, 87, 24, In order: false. What I want it to be printing out is 941, 874, 102, 96, 87, 24, In order: false. In regards to the merging of my two array lists, I am not sure if it will merge correctly as I am not sure how to convert this line of code to print out an ArrayList. I used these two lines of code to print out my merged Arrays originally.
int merged[] = merge(num3,num4);
print(merged);
Here are the methods I am using to reverse the arrayList and the method to merge the two:
/*** <<< CODE NOT COMPLETE >>>
* reverses the order of the elemets in the array
***/
public static void reverse(ArrayList <Integer> a)
{
for (int i = 0; i < a.size()/2; i++)
{
int reverseOrder = a.get(i);
a.set(i, a.size() - 1 - i);
a.set(a.size() - 1 - i, reverseOrder);
}
}
/*** <<< CODE NOT COMPLETE >>>
* merges two sorted arrays into 1 new array, maintains the sorted order
***/
public static ArrayList <Integer> merge (ArrayList <Integer> a, ArrayList <Integer> b)
{
ArrayList <Integer> merge = new ArrayList <Integer> (a.size() + b.size());
int i = 0, j = 0, k = 0;
while (i < a.size() && j < b.size())
{
if (a.get(i) < b.get(j))
{
merge.set(k++, a.get(i++));
}
else
{
merge.set(k++, b.get(j++));
}
}
while (i < a.size())
{
merge.set(k++, a.get(i++));
}
while (j < b.size())
{
merge.set(k++, b.get(i++));
}
return merge;
}
Upvotes: 1
Views: 214
Reputation: 201429
In public static void reverse(ArrayList <Integer> a)
, this
a.set(i, a.size() - 1 - i); // <-- the index, not the value.
a.set(a.size() - 1 - i, reverseOrder);
should be
a.set(i, a.get(a.size() - 1 - i)); // <-- the value.
a.set(a.size() - 1 - i, reverseOrder);
You also have a typo in your merge
, where you use i++
in the final loop. But really, you should prefer the List
interface. Also, you don't need k
since the List
keeps an internal index. You also don't need to explicitly size your List
(but I did here to be consistent with your code). And, I would store the size
(s). Like,
public static List<Integer> merge(List<Integer> a, List<Integer> b) {
final int aLen = a.size(), bLen = b.size();
List<Integer> al = new ArrayList<>(aLen + bLen);
int i = 0, j = 0;
while (i < aLen && j < bLen) {
if (a.get(i) < b.get(j)) {
al.add(a.get(i++));
} else {
al.add(b.get(j++));
}
}
while (i < aLen) {
al.add(a.get(i++));
}
while (j < b.size()) {
al.add(b.get(j++));
}
return al;
}
Upvotes: 1