Insertion sort sorting an ArrayList problems - java

now I have been at this for a while and there is an error I am having. Now the program I am making is an address book, and I am using an insertion sort to sort an arraylist of objects which I call books(address entries). Now I soon discovered that my sorter is not sorting properly so I made a simple program to test the sorter and again it does not work. I was wondering if you guys could have a look at it and help me out.
Here is my Sorter:
import java.util.ArrayList;
public class Sorts {
/**
* Sorts and array of integer from low to high
* pre: none
* post: Integers has been sorted from low to high
*/
public static void insertionSort(ArrayList<String> test) {
Comparable temp;
int previousIndex;
ArrayList<String> objectSort = test;
for (int i = 1; i < objectSort.size(); i++) {
temp = objectSort.get(i);
previousIndex = i - 1;
while ((objectSort.get(previousIndex).compareTo((String) temp)) == 1 && (previousIndex > 0)) {
objectSort.set(previousIndex + 1, objectSort.get(previousIndex));
previousIndex -= 1; //decrease index to compare current item with next previous item
}
if (objectSort.get(previousIndex).compareTo((String) temp) == 1) {
/* shift item in first element up into next element */
objectSort.set(previousIndex + 1, objectSort.get(previousIndex));
/* place current item at index 0 (first element */
objectSort.set(previousIndex, (String) temp);
} else {
/* place current item at index ahead of previous item */
objectSort.set(previousIndex + 1, (String) temp);
}
}
}
}
My simple program to test it is:
import java.util.ArrayList;
public class Main {
public static void main(String[] args){
ArrayList<String> test = new ArrayList<String>();
test.add("Roxy");
test.add("Proxy");
test.add("Moxy");
test.add("Samuel Adams");
Sorts.insertionSort(test);
System.out.println(test);
}
}
To sum it up, I am having troubles with my ArrayList sorter. The problem is it wont sort correctly and I do not know why. Thank you so much in advance. If you have any questions feel free to ask. :)

First problem: you're expecting compareTo to always return 1 for "greater than". It just returns a value greater than 0 which may be a different positive integer. So both your == 1 comparisons should be > 0.
There may be other problems, but that's the first one I'd look at.

Related

sorting lists in ascending order, with a System out of bound error

My code sorts lists in ascending order when the length of a list is 3, the code works perfectly, however, when the length of a list increases and the number of inserted variables increase, the output is either System out of bound or it doesn't sort it correctly.
public class Lists {
int [] lists;
int itemcount;
public Lists(int l) {
lists =new int[l];
itemcount=0;
}
public void insert(int x) {
if(itemcount==0) {
lists[itemcount]=x;
itemcount++;
}
else {
for(int i=itemcount-1;i>=0;i--) {
if(lists[i]>x) {
lists[i+1]=lists[i];
lists[i]=x;
itemcount++;
}
else {
lists[i+1]=x;
itemcount++;
}
}
}
}
public static void main(String[]args) {
Lists s=new Lists(5);
s.insert(9);
s.insert(4);
s.insert(6);
s.insert(5);
s.insert(8);
for (int i=0;i<s.lists.length;i++) {
System.out.print(s.lists[i]);
}
}
}
This is insertion sort, each time we insert an item to the already sorted list. All the elements greater than the item is moved ahead. So we need to stop at the right position so it require additional condition in the iteration loop.
see how it works , https://en.wikipedia.org/wiki/File:Insertion-sort-example-300px.gif
public void insert(int x) {
int i;/*Insertion position */
for(i=itemcount-1;i>=0 && lists[i]>x;i--) {
lists[i+1]=lists[i];
}
lists[i+1]=x;
itemcount++;
}
The "sorting" part does not seem to be correct, itemcount is incremented in loop several times instead of 1 when only 1 element is inserted.
Thus, the index should be detected where the new item has to be inserted, then the elements shoulds be shifted to the end of lists array.
Also, a case needs to be addressed when there is an attempt to insert more elements than lists.length: print a message and ignore the attempt, throw an exception, or increase the size of lists (e.g. using Arrays.copyOf)
Linear search of the id is as follows as the size of lists is relatively small (if the lists size is large enough, a binary search should be used)
public void insert(int x) {
if (itemcount == lists.length) {
lists = Arrays.copyOf(lists, lists.length * 2);
}
int id = 0;
for (; id < itemcount; id++) {
if (x <= lists[id]) {
break; // insert in id
}
}
for (int i = itemcount; i > id; i--) {
lists[i] = lists[i - 1];
}
lists[id] = x;
itemcount++;
}
Also, when printing the contents of lists it may better to use itemcount as a limit, unless it's needed to show 0's as empty elements.
So, the output for the following test setup:
Lists s = new Lists(5);
s.insert(9); s.insert(4); s.insert(6);
s.insert(5); s.insert(8); s.insert(5);
s.insert(2);
for (int i=0;i<s.itemcount;i++) {
System.out.print(s.lists[i] + " ");
}
Output:
2 4 5 5 6 8 9

Randomizing set of duplicate arrays in Java without repeating elements

In my problem I have few arrays with numbers 1 - 3,
[1,2,3], [1,2,3]
I combined the arrays into one full array,
[1,2,3, 1,2,3]
I need to randomize the array each run, so that no element repeats.
For example, this would work
[1, 2, 1, 3, 2, 3]
but this would not.
[1,2,2,3,1,3]
I chose 1,2,3 to simplify it, but my arrays would consist of the numbers 1 - 6. The idea remains the same though. Is there an algorithm or easy method to accomplish this?
This is a heuristic solution for random shuffling not allowing consecutive duplicates. It applies to lists, but it's easy to transfer it to arrays as it does only swapping and no shift operations are required. It seems to work in the majority of cases for lists consisting of millions of elements and various density factors, but always keep in mind that heuristic algorithms may never find a solution. It uses logic from genetic algorithms, with the exception that this version utilizes one individual and selective mutation only (it's easy to convert it to a real genetic algorithm though), but it's simple and works as follows:
If a duplicate is found, try swapping it with a random element after it; if not possible, try swapping it with an element prior to it (or vice versa). The key point here is the random position for exchanging elements, so as to keep a better uniform distribution on random output.
This question has been asked in alternative forms, but I couldn't find an acceptable solution yet. Unfortunately, as most of the proposed answers (except for the "greedy" extensive re-shuffling till we get a match or computing every combination), this solution does not provide a perfect uniform distribution, but seems to minimize some patterns, :( still not possible to remove every pattern, as you see below. Try it and post any comments for potential improvements.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
//Heuristic Non-Consecutive Duplicate (NCD) Shuffler
public class NCDShuffler {
private static Random random = new Random();
//private static int swaps = 0;
public static <T> void shuffle (List<T> list) {
if (list == null || list.size() <= 1) return;
int MAX_RETRIES = 10; //it's heuristic
boolean found;
int retries = 1;
do {
Collections.shuffle(list);
found = true;
for (int i = 0; i < list.size() - 1; i++) {
T cur = list.get(i);
T next = list.get(i + 1);
if (cur.equals(next)) {
//choose between front and back with some probability based on the size of sublists
int r = random.nextInt(list.size());
if ( i < r) {
if (!swapFront(i + 1, next, list, true)) {
found = false;
break;
}
} else {
if (!swapBack(i + 1, next, list, true)) {
found = false;
break;
}
}
}
}
retries++;
} while (retries <= MAX_RETRIES && !found);
}
//try to swap it with an element in a random position after it
private static <T> boolean swapFront(int index, T t, List<T> list, boolean first) {
if (index == list.size() - 1) return first ? swapBack(index, t, list, false) : false;
int n = list.size() - index - 1;
int r = random.nextInt(n) + index + 1;
int counter = 0;
while (counter < n) {
T t2 = list.get(r);
if (!t.equals(t2)) {
Collections.swap(list, index, r);
//swaps++;
return true;
}
r++;
if (r == list.size()) r = index + 1;
counter++;
}
//can't move it front, try back
return first ? swapBack(index, t, list, false) : false;
}
//try to swap it with an element in a random "previous" position
private static <T> boolean swapBack(int index, T t, List<T> list, boolean first) {
if (index <= 1) return first ? swapFront(index, t, list, false) : false;
int n = index - 1;
int r = random.nextInt(n);
int counter = 0;
while (counter < n) {
T t2 = list.get(r);
if (!t.equals(t2) && !hasEqualNeighbours(r, t, list)) {
Collections.swap(list, index, r);
//swaps++;
return true;
}
r++;
if (r == index) r = 0;
counter++;
}
return first ? swapFront(index, t, list, false) : false;
}
//check if an element t can fit in position i
public static <T> boolean hasEqualNeighbours(int i, T t, List<T> list) {
if (list.size() == 1)
return false;
else if (i == 0) {
if (t.equals(list.get(i + 1)))
return true;
return false;
} else {
if (t.equals(list.get(i - 1)) || (t.equals(list.get(i + 1))))
return true;
return false;
}
}
//check if shuffled with no consecutive duplicates
public static <T> boolean isShuffledOK(List<T> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i).equals(list.get(i - 1)))
return false;
}
return true;
}
//count consecutive duplicates, the smaller the better; We need ZERO
public static <T> int getFitness(List<T> list) {
int sum = 0;
for (int i = 1; i < list.size(); i++) {
if (list.get(i).equals(list.get(i - 1)))
sum++;
}
return sum;
}
//let's test it
public static void main (String args[]) {
HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
//initialise a list
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(1);
list.add(2);
list.add(3);
/*for (int i = 0; i<100000; i++) {
list.add(random.nextInt(10));
}*/
//Try to put each output in the frequency Map
//then check if it's a uniform distribution
Integer hash;
for (int i = 0; i < 10000; i++) {
//shuffle it
shuffle(list);
hash = hash(list);
if (freq.containsKey(hash)) {
freq.put(hash, freq.get(hash) + 1);
} else {
freq.put(hash, 1);
}
}
System.out.println("Unique Outputs: " + freq.size());
System.out.println("EntrySet: " + freq.entrySet());
//System.out.println("Swaps: " + swaps);
//for the last shuffle
System.out.println("Shuffled OK: " + isShuffledOK(list));
System.out.println("Consecutive Duplicates: " + getFitness(list));
}
//test hash
public static int hash (List<Integer> list) {
int h = 0;
for (int i = 0; (i < list.size() && i < 9); i++) {
h += list.get(i) * (int)Math.pow(10, i); //it's reversed, but OK
}
return h;
}
}
This is a sample output; it's easy to understand the issue with the non-uniform distribution.
Unique Outputs: 6
EntrySet: [1312=1867, 3121=1753, 2131=1877, 1321=1365, 1213=1793, 1231=1345]
Shuffled OK: true
Consecutive Duplicates: 0
You could use Collections.shuffle to randomize the list. Do it in a while loop, until the list passes your constraint.
If the arrays are relatively small, it would not be too hard for you just to combine the two arrays, randomize it then check the numbers, and if there are too same numbers just shift one over or just randomize it again.
There's no pre-written algorithm that I know of (which doesn't mean one doesn't exist), but the problem is easy to understand and the implementation is straightforward.
I will offer two suggestions dependent on if you want to build a valid array or if you want to build an array and then check its validity.
1 - Create some collection (Array, ArrayList, etc) that contains all of the possible values that will be included in your final array. Grab one of those values and add it to the array. Store a copy of that value in a variable. Grab another value from the possible values, check that it's not equal to your previous value, and add it to the array if it's valid.
2 - Create an array that contains the number of values you want. Check that item n != item n+1 for all items except the last one. If you fail one of those checks, either generate a new random value for that location or add or subtract some constant from the value at that location. Once you have checked all of the values in this array, you know you have a valid array. Assuming the first and last values can be the same.
The most optimal solution, I can think of, is to count the number of occurrences of each value, logically creating a "pool" for each distinct value.
You then randomly choose a value from any of the pools that are not the value of the previous selection. The random selection is weighted by pool sizes.
If a pool is more than half the size of all remaining values, then you must choose from that pool, in order to prevent repetition at the end.
This way you can produce result fast without any form of retry or backtracking.
Example (using letters as values to clarify difference from counts):
Input: A, B, C, A, B, C
Action Selected Pools(Count)
A(2) B(2) C(2)
Random from all 3 pools A A(1) B(2) C(2)
Random from B+C pools C A(1) B(2) C(1)
Random from A+B pools (1:2 ratio) A A(0) B(2) C(1)
Must choose B (>half) B A(0) B(1) C(1)
Random from A+C, so C C A(0) B(1) C(0)
Must choose B (>half) B A(0) B(0) C(0)
Result: A, C, A, B, C, B

Given a stream of number, like 1,3,5,4,6,9, I was asked to print them like 1,3-6,9

Given a stream of number, like 1,3,5,4,6,9, I was asked to print them like 1,3-6,9. My approach was to hold min 2 numbers in a maxHeap and max 2 numbers in a minHeap. And I have come up with a following solution. Do you have any suggestion to make it more optimized? Its time complexity is O(nlogn).
public static ArrayList<Integer> mergingMiddleNums (int[] arr){
if (arr == null || arr.length < 3){
throw new IllegalArgumentException();
}
ArrayList<Integer> result = new ArrayList<>();
Queue<Integer> minHeap = new PriorityQueue<>();
Queue<Integer> maxHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
#Override
public int compare(Integer num1, Integer num2) {
return num2-num1;
}
});
for (int i = 0 ; i < 2 ; i++){
minHeap.add(arr[i]);
}
for (int i = 0 ; i < 2 ; i++){
maxHeap.add(arr[i]);
}
for (int i = 2 ; i <arr.length; i++){
if(arr[i] > minHeap.peek()){
minHeap.poll();
minHeap.add(arr[i]);
}
}
result.add(minHeap.poll());
result.add(minHeap.poll());
for (int i = 2 ; i <arr.length; i++){
if(arr[i] < maxHeap.peek()){
maxHeap.poll();
maxHeap.add(arr[i]);
}
}
result.add(maxHeap.poll());
result.add(maxHeap.poll());
Collections.sort(result);
return result;
}
It depends on whether your output needs to stream or not. Let's start with non-streaming output, because your current implementation addresses this.
Your code's overall complexity will be, at best, O(nLog(n)), but you can radically simplify your implementation by storing every incoming number in a collection, converting it to an array, and sorting it, before scanning over the items sequentially to identify continuous ranges. The most expensive operation here would be the sort, which would define your runtime. To save space, you could use a set or heap collection to avoid storing duplicates (the formation of which will be somewhere near O(nLog(n)) - which being the same runtime, remains collapsed at a total runtime of O(nLog(n))
If your code is expected to stream the printing along with output, that is, to print ranges as they are formed and move to the next range whenever the next number encountered is not directly adjacent to the current range, you can do it in O(n) by storing the numeric bounds of the current range as you go and either printing and resetting them if the currently-examined number is not adjacent or inside the bounds, or by expanding the bounds if it is.
A possible implementation would be to use a hashtable to store wether each integer was present in the input values or not. Then, it's simply a matter of iterating from the min value to the max and use the hashtable to find out where are the number clusters.
Such implementation would basically be O(n) with n=max-min (and not number of items in list). So if you have many numbers within a reasonably small range of values, then you could be better than a sort-based approach.
import java.util.HashMap;
import java.util.Map;
class Test {
private int min=0, max=-1;
private Map<Integer,Integer> map=new HashMap<Integer,Integer>();
public static void main(String args[]) {
int[] input={1,3,5,4,6,9};
Test t = new Test();
t.readNumbers(input);
t.outputRanges();
}
public void readNumbers(int[] values) {
// Get min and max values, and store all existing values in map
for(int v:values) {
if(first || v<min) min=v;
if(first || v>max) max=v;
first=false;
map.put(v, 1);
}
}
public void outputRanges() {
// Iterate from min to max and use map to find out existing
// values
int last=min-2;
boolean inRange=false;
first=true;
for(int i=min;i<=max;++i) {
if(map.get(i)==null) continue;
if(i==last+1) {
inRange=true;
} else {
if(inRange) {
closeRange(last);
inRange=false;
}
output(i);
}
last=i;
}
if(inRange) closeRange(last);
}
private boolean first;
private void commaUnlessFirst() {
if(!first) System.out.printf(",");
first=false;
}
private void output(int i) {
commaUnlessFirst();
System.out.printf("%d", i);
}
private void closeRange(int i) {
System.out.printf("-%d", i);
}
}

Inserting objects into arraylist

I have an arraylist of 50 RANDOM integers. I ask a user to remove a number and all occurences of that number are removed from the list. I did that using
while (randInts.contains(removeInt) )
{
if (randInts.get(i) == removeInt)
randInts.remove(randInts.get(i));
i++;
}
System.out.println("\n" + randInts.toString());
System.out.println("\n" + randInts.size());`
The other part of the problem is to prompt the user to enter another number. The removed number from above is inserted after each occurrence of the second prompted number. I am having issues with the second part as I keep getting IndexOutOfBoundsException.
Use a LinkedList instead; it's a much better choice when you need in-order traversal but not really random access, and when you need to insert and remove elements in the middle of the list.
You can accomplish what you're wanting (removing all instances of removeInt and inserting removeInt after every instance of insertAfterInt) with a simple traversal of the list's iterator:
ListIterator<Integer> li = randInts.listIterator();
while(li.hasNext()) {
int i = li.next();
if(removeInt == i) // assumes removeInt is an int; use equals() for Integer
li.remove();
if(insertAfterInt == i)
li.add(removeInt); // the iterator will skip this element, so it won't get removed
}
I see two big issues: You're not bounding i to anything, and you wrote an n^2 loop (you can do this in linear time).
You're shrinking the size of the `List` as you go...take this simple example:
Say you want to remove all instances of 5
Given a list that looks like {1,2,3,5,5}
When i = 3 you will remove the first 5, making the list look like: {1,2,3,5}
then you will attempt to remove the element at i = 4, but that element you want to remove is really now at i = 3, and you'll get the IndexOutOfBoundsException
You don't want to use a `contains`, as this expands the worst case performance of your loop to n^2, this would be faster:
int size = randInts.size() - 1;
for (int i = size; i >= 0; i--){
if (randInts.get(i).equals(removeInt))
randInts.remove(i);
}
while (randInts.contains(removeInt) )
{
if(i<randInts.size());
{
if (randInts.get(i) == removeInt)
randInts.remove(randInts.get(i));
}//if
i++;
}while
I am guessing you are starting with a collection of 50 items (randInts) and removing the items that users enter (i)?
If that is the case, once your remove an item, your collection then only 49 indexes left and get gets by the index. Try something like...
if (randInts.contains(i)){
randInts.remove(randInts.indexOf(i));
}
This is n^2, but it should work
int i = 0;
while(i < loFnumbers.size()){
if(loFnumbers.get(i) == removeInt){
loFnumbers.remove(i);
continue;
}
i++;
}
Here's an approach that avoids any state mutation (i.e. randInts is never modified):
package so;
import java.util.ArrayList;
public class SO_18836900 {
public static void main(String[] args) {
// build a collection of random ints
ArrayList<Integer> randInts = new ArrayList();
for (int i = 0; i < 50; i ++) {
randInts.add((int)(Math.random() * 5));
}
// create a collection with all 3s filtered out
ArrayList<Integer> filtered = filterOut(randInts, 3);
System.out.println(filtered);
System.out.println(filtered.size());
// create a collection with a 99 inserted after each 4
ArrayList<Integer> insertedAfter = insertAfter(randInts, 4, 99);
System.out.println(insertedAfter);
System.out.println(insertedAfter.size());
}
static ArrayList<Integer> filterOut(Iterable<Integer> xs, int toRemove) {
ArrayList<Integer> filteredInts = new ArrayList();
for (int x : xs) {
if (x != toRemove) filteredInts.add(x);
}
return filteredInts;
}
static ArrayList<Integer> insertAfter(Iterable<Integer> xs, int trigger, int toInsert) {
ArrayList<Integer> insertedAfter = new ArrayList();
for (int x : xs) {
insertedAfter.add(x);
if (x == trigger) insertedAfter.add(toInsert);
}
return insertedAfter;
}
}
if (randInts.get(i) == removeInt)
randInts.remove(randInts.get(i));
i++;
You're never checking stopping conditions. Fix is:
while (randInts.contains(removeInt) )
{
i=0;
while(i<randInts.size()){
if (randInts.get(i) == removeInt)
randInts.remove(randInts.get(i));
i++;
}
}
Dont use == on "Integers" you are comparing references.
Either unbox into int or use equals(

Need help streamlining my Merge Sort implementation [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am building a class of sortable ArrayLists which extends ArrayList. The goal is to be able to call a sort method on a SortDoubleArray, and have that array be sorted via the method described. I got Quicksort, Insertion Sort, Bubble Sort, and Selection Sort all working as I want. I am having some difficulty with Merge Sort, however.
The sort works, but due to the way the recursion involved is working, I am forced reset the contents of the list to be the method applied to itself.
First, here is the tester class. It shows how the other sorts are being implemented. If I did a poor job explaining my issue, hopefully you will see the difference in how the mergeSort() method must be used.
public class SortTester
{
/**
* #param args
*/
public static void main(String[] args)
{
SortDoubleArray list = new SortDoubleArray();
// Code to fill an array with random values.
//list.quickSort();
//list.insertionSort();
//list.selectionSort();
//list.bubbleSort();
list = list.mergeSort();
// Code to print the sorted array.
}
}
Next, here is the SortDoubleArray class. All of the other sorts but insertionSort (to serve as an example of one working the way I want) have been removed for brevity.
public class SortDoubleArray extends ArrayList<Double>
{ // Start of class.
private static final long serialVersionUID = 1271821028912510404L;
/**
* Progresses through the elements one at a time inserting them in their proper place
* via swaps.
*/
public void insertionSort()
{ // Start of insertionSort.
int current = 1;
while (current < size())
{
int i = current;
boolean placeFound = false;
while(i > 0 && !placeFound)
{
if (get(i) < get(i - 1))
{
double temp = get(i);
set(i, get(i - 1));
set(i - 1, temp);
i -= 1;
}
else
{
placeFound = true;
}
}
current += 1;
}
} // End of insertionSort.
/**
* Triggers the recursive mSort method.
* #return
*/
public SortDoubleArray mergeSort()
{ // start of mergeSort.
return mSort(this);
} // End of mergeSort.
/**
* Separates the values each into their own array.
*/
private SortDoubleArray mSort(SortDoubleArray list)
{ // Start of mSort.
if (list.size() <= 1)
{
return list;
}
SortDoubleArray left = new SortDoubleArray();
SortDoubleArray right = new SortDoubleArray();
int middle = list.size() / 2;
for (int i = 0; i < middle; i += 1)
{
left.add(list.get(i));
}
for (int j = middle; j < list.size(); j += 1)
{
right.add(list.get(j));
}
left = mSort(left);
right = mSort(right);
return merge(left, right);
} // End of mSort.
/**
* Merges the separated values back together in order.
*/
private SortDoubleArray merge(SortDoubleArray left, SortDoubleArray right)
{ // Start of merge.
SortDoubleArray result = new SortDoubleArray();
while (left.size() > 0 || right.size() > 0)
{
if (left.size() > 0 && right.size() > 0)
{
if (left.get(0) <= right.get(0))
{
result.add(left.get(0));
left.remove(0);
}
else
{
result.add(right.get(0));
right.remove(0);
}
}
else if (left.size() > 0)
{
result.add(left.get(0));
left.remove(0);
}
else if (right.size() > 0)
{
result.add(right.get(0));
right.remove(0);
}
}
return result;
} // End of merge.
} // End of class.
Please give me some ideas on how I can alter the mergeSort() / mSort() functions within the SortDoubleArray class to have the same implementation as the rest of the sorts.
Thank you!
Given that mSort and merge methods are correct, how about this ?
public void mergeSort()
{ // start of mergeSort.
SortDoubleArray result = mSort(this);
clear();
addAll(result);
} // End of mergeSort.
The relevant line in your test would then be:
list.mergeSort();
Good luck!
Currently your mergeSort() and merge() functions are each creating new SortedDoubleArray objects. Ideally you would do everything in-place without creating new arrays, the amount your creating and copying will create quite a performance hit for your algorithm.
So your methods would have prototypes something like this:
private SortDoubleArray mSort(SortDoubleArray list, int startIndex, int length)
private SortDoubleArray merge(SortDoubleArray list,
int leftIndex, int leftlength,
int rightIndex, int rightlength)
Then use ArrayList.set and .get with a temporary variable to do the swapping in-place. This will mean you're only working on a single array and not creating any new unnecessary ones.
Does this help? Let me know if I understood the issue or you need more explanation.
Note that int endIndex can also work instead of int length

Categories

Resources