Reputation: 1531
here is my code, i can't figure out why it doesn't work. This algorithm have to sort array but when i run it, it retreive me the same array.
import java.util.Arrays;
public class BubbleSorted1 {
public static void main(String[] args) {
int[] data = {40,20,50,30,10};
sort(data);
System.out.println(Arrays.toString(data));
}
public static void sort(int[] array){
for(int barrier = array.length-1; barrier >= 0; barrier--){
for(int index = 0; index < barrier; index++){
if(array[index] > array[index] + 1){
int tmp = array[index];
array[index] = array[index + 1];
array[index + 1] = tmp;
}
}
}
}
}
Upvotes: 0
Views: 79
Reputation: 222
You write array[index] > array[index] + 1
. This should probably have been array[index] > array[index + 1]
as the check you do is always false.
Upvotes: 3
Reputation: 1454
You have a typo here:
if(array[index] > array[index] + 1){
I think you meant:
if(array[index] > array[index + 1]){
The first condition can never be true because a number (the value contained in the index
of the array) won't never be greater than itself plus one.
Upvotes: 2
Reputation: 1337
Try this.. Only thing You need to change is IF condition
public static void sort(int[] array){
for(int barrier = array.length-1; barrier >= 0; barrier--){
for(int index = 0; index < barrier; index++){
if(array[index] > array[index+1]){
int tmp = array[index];
array[index] = array[index + 1];
array[index + 1] = tmp;
}
}
}
Upvotes: 0