0

Can someone please help with exchange method. I have an algorithm


  1. Assign boolean variable b to true.
  2. While b is true, perform the following steps: a) Assign false to b. b) Change i from 0 to the end of the array in step 2 and execute for each value of i:

    • if the element with the number i is larger than the element with the number i + 1 then: 1) Swap array elements with numbers i and i + 1;
    • assign the value b to true.
  3. Change i from 1 to the end of the array in step 2 and execute each value of i:

    • if the element with the number i is larger than the element with the number i + 1 then: 1) Swap array elements with numbers i and i + 1;
    • assign the value b to true.
public static void firstmethod(int[] a) {
    boolean b = true; // boolean =true
    while (b = true) {
        b = false;
        for (int i = 0; i <= a.length; i = i + 2) //Do konca massiva A,wag 2,i i=0!
        {
            if (a[i] > a[i + 1]) {
                a[i] = a[i + 1];//menajem mestami 
                b = true;
            }
        }
        for (int i = 1; i <= a.length; i = i + 2) //Do konca massiva A,wag 2,i i=0!
        {
            if (a[i] > a[i + 1]) {
                a[i] = a[i + 1];//menajem mestami 
                b = true;
            }

        }
    }
}

Main problem is when im initializing array I'm getting out of bounds error. I understand that this is because of a[i+1],but I dont understand how to fix it....

Thanks

Kaan
  • 5,434
  • 3
  • 19
  • 41

1 Answers1

0

Few things on a quick read:

  • while (b == true) {}
  • for (int i = 0; i < a.length - 2; i = i + 2) {}
  • a[i] = a[i + 1] is only half of a swap. You are missing a[i + 1] = a[i] but by now your a[i] has new value already, so you have to think a bit (or google variable swap).
diginoise
  • 7,352
  • 2
  • 31
  • 39