Can someone please help with exchange method. I have an algorithm
- Assign boolean variable b to true.
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.
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