-2

I'm not new at Java, but I'm in JUnit. I'm having a problem with a simple for loop. I'm ordering array elements with bubble sorting, but I don't know why the two last elements disappear during the loop. I know it will be a little tiny thing, but I can't find the mistake. Could you help me, please?

This is my class:

package exercise5;

public class Ejercicio5 {

    public static int[] sort(int[] arrayNums) {

        // array that I have tried: {6,5,8,3,7,1}; [6]
        System.out.println("size: " + arrayNums.length);
        for (int j = 0; j < arrayNums.length; j++) {
            System.out.println("j:" + j);
            if (arrayNums[j] > arrayNums[j + 1]) {
                System.out.println("entra");
                int numGuardado = arrayNums[j + 1];
                arrayNums[j + 1] = arrayNums[j];
                arrayNums[j] = numGuardado;
            }
            print(arrayNums);
        }
        return arrayNums;
    }

    public static void print(int[] arrayParaImprimir) {
        System.out.println("Array:");
        for (int j = 0; j < arrayParaImprimir.length; j++) {
            if (j != arrayParaImprimir.length - 1) {
                System.out.print(arrayParaImprimir[j] + ", ");
            } else {
                System.out.print(arrayParaImprimir[j] + "\n");
            }
        }
    }
}

My TestClass with JUnit5:

package exercise5;

import org.junit.Assert;
import org.junit.jupiter.api.Test;

import junit.framework.TestCase;

public class Ejercicio5Test extends TestCase{
    
    @Test
    public void resultadoCorrecto(){
        int[] correct = {1,3,5,6,7,8};
        int[] array = {6,5,8,3,7,1};
        int[] result = Ejercicio5.sort(array);
        Assert.assertArrayEquals(result, correct);
    }
    
    @Test
    public void resultadoIncorrecto(){
        int[] correct = {1,3,5,6};
        int[] array = {3,5,6,1};
        int[] result = Ejercicio5.sort(array);
        Assert.assertArrayEquals(result, correct);
    }
}

When j is equal to 4, the ordering is doing: 5, 6, 3, 7, 1, 8 but when j passed to 5, two elements disappear. In addition, in my Test class there are only two methods, but, when I run it, it recognises one more and give me an error:

enter image description here

This is the array that I have tried {1,3,5,6,7,8} and this is that I expected {5,6,3,7,1,8} with 6 of array's size, not element disappearing.

enter image description here

This is the output in console. NOT ArrayIndexOutOfBounds. Only disappear 2 elements, and the size changes, not throwing any exceptions:

size: 6
j:0
entra
Array:
5, 6, 8, 3, 7, 1
j:1
Array:
5, 6, 8, 3, 7, 1
j:2
entra
Array:
5, 6, 3, 8, 7, 1
j:3
entra
Array:
5, 6, 3, 7, 8, 1
j:4
entra
Array:
5, 6, 3, 7, 1, 8
j:5
size: 4
j:0
Array:
3, 5, 6, 1
j:1
Array:
3, 5, 6, 1
j:2
entra
Array:
3, 5, 1, 6
j:3
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
h1294
  • 1
  • 1
  • 1
    Your loop condition is `j < arrayNums.length`, but inside that loop you are using `arrayNums[j + 1]`, which will go out of array bounds. – adnan_e Nov 14 '22 at 12:08
  • Surely Junit would have reported that the code failed with an exception? – access violation Nov 14 '22 at 12:35
  • Short: Bubble sorting loops through the array again and again until no one element exchanged. So a simple for cycle cannot do this. You need a while with a for in. – szeak Nov 14 '22 at 13:24
  • @szeak I have update what the console output is, only quit 2 elements, not all of them. That's my question – h1294 Nov 14 '22 at 14:59
  • @access violation I have update my question with a picture of JUnit warning problem. Maybe it can help to answer me – h1294 Nov 14 '22 at 15:03
  • The ArrayIndexOutOfBounds exception is visible right there in the posted image, indicating the exact line your code failed on. – access violation Nov 14 '22 at 18:07
  • @h1294 Ok, after checking your output, it looks like the outputs from j = 0 to 5 comes from the first call of sort called by `resultadoCorrecto()`, then we see "size: 4" again, which is a new call to sort function, which was called from `resultadoIncorrecto()`, where your array is 4 long. Nothing disappeared, just you looked your output from wrong point of view. When you debug your code you will see that. Or put print "Call from ..." at before calling sort. – szeak Nov 15 '22 at 09:14

3 Answers3

0
for (int j = 0; j < arrayNums.length; j++) {

This loops for every number in the input. Then you..

if (arrayNums[j] > arrayNums[j + 1]) {

Compare this to the next number in the input. On the last loop, you are therefore comparing the last number (arrayNums[j]) with the.. number after that. Which doesn't exist, hence, ArrayIndexOutOfBoundsEx.

You want to loop one fewer.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

You missed one loop here is the correct code -

public class Ejercicio5 {
//you don't need to return as it modifies exiting array
 public static void sort(int arr[])
{
    int n = arr.length;
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - i - 1; j++)
            if (arr[j] > arr[j + 1]) {
                // swap arr[j+1] and arr[j]
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
}

/* Prints the array */
public static void printArray(int arr[])
{
    int n = arr.length;
    for (int i = 0; i < n; ++i)
        System.out.print(arr[i] + " ");
    System.out.println();
}


public static void main(String args[])
{
    int[] array = {6,5,8,3,7,1};
    Ejercicio5.sort(array);
    System.out.println("Sorted array");
    Ejercicio5.printArray(array);
}

}

output - Sorted array 1 3 5 6 7 8

and your testcases should work now with minor changes

Sagar Kale
  • 97
  • 1
  • 7
  • I have the return because I use it in my Tests Class. I have the BubbleSort exercise corrected, what I want to know is what is my problem in my question's loop, not how to do BubbleSort exercise correct, but thank you – h1294 Nov 14 '22 at 15:09
0

If you run the JUnit test, it runs all the methods annotated by @Test.
Your output exactly reflects the 2 calls of your sort function, first from resultadoCorrecto() to line "j:5", second call from resultadoIncorrecto(), what outputs lines after that (from "size: 4").
So nothing has disappeared.
resultadoCorrecto() calls sort function with an array size of 6.
resultadoIncorrecto() calls sort function with an array size of 4.

Your bubble sort problem:
The for loop must go until index < length-1.
You must bubbling up all the bubbles with another for cycle around. (See Sagar Kale's answer.)

szeak
  • 325
  • 1
  • 7
  • OMG, that's correct!! I can't mark this answer correct due to need 15 points of reputation! But that's it! I have delete several times the JUnit Test without thinking the array's size of two methods is different! And everytime thinking the array's size was changing! What a silly thing!! Thank you @szeak!!!! – h1294 Nov 17 '22 at 09:30