0

This is my first question here, and I truly am not sure if I am doing something wrong, or if its even possible, I saw it suggested here on stack overflow, however I am not sure if it works for my specific situation.

I am doing a challenge on Hackerrank.com, and It is making me enter an Array(not an ArrayList) and it wants me to swap the items until they are all in ascending order.

I know I can use a temp variable to hold one of the values and swap it out, but I saw someone recommend to use Collections.swap and here is how I tried to implement it:

for (int i = 0; i < n; i++){
        int numSwaps = 0;
        for(int j = 0; j < n - 2; j++) {
         if(a[j] > a[j+1]) {
                Collections.swap(Arrays.asList(a), j,j+1);
                numSwaps += 1;
            }
         totalSwaps += numSwaps;
        }
        if(numSwaps == 0) {
            break;
        }
    }

Am i doing using it wrong? Or is it something that is just not possible?

Thank you very much!

  • What happens after you run your code? Can you print the input and the output so we can see what's going on? – Michael Jan 29 '18 at 20:02
  • So when I run this code: it gives me an ArrayIndexOutOfBounds error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at java.util.Arrays$ArrayList.set(Arrays.java:3846) at java.util.Collections.swap(Collections.java:497) at com.cloudeasegroup.app.Main.main(Main.java:81) – Johnny Villegas Jan 29 '18 at 20:05
  • You don't seem to be checking whether the objects need to be swapped - you're just swapping everything regardless. This will change the order, sure, but probably not to the order you want. – Dawood ibn Kareem Jan 29 '18 at 20:07
  • 2
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Tom Jan 29 '18 at 20:10

0 Answers0