Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo. Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo.
public static ArrayList<Integer> BubbleSort(ArrayList<Integer> data) {
ArrayList<Integer> result = data; //Resultado
boolean swaped = false; //Variable en caso de que no haya intercambio
int i = 0;
int j = 0;
while (i < result.size() - 1) {
swaped = false;
i++;
while (j < result.size() - i - 1) {
//obtenemos los valores
Integer pos = result.get(j);
Integer next = result.get(j + 1);
//si la pos es mayor que el siguiente intercambia
if (pos > next) {
result.set(j, next);
result.set(j + 1, pos);
swaped = true;
}
System.out.println(result);
j++;
}
if (!swaped) {//si no hubo intercambio se acaba el método
break;
}
}
return data;
}
Results:
Before :
[13, 7, 18, 5, 2]
[7, 13, 18, 5, 2]
[7, 13, 18, 5, 2]
[7, 13, 5, 18, 2]
After :
[7, 13, 5, 18, 2]
BUILD SUCCESSFUL (total time: 0 seconds)
Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo. Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo.
Este el codigo corregido, pero sigue saliendo los mismo resutados.
public static ArrayList<Integer> BubbleSort(ArrayList<Integer> data) {
ArrayList<Integer> result = data; //Resultado
boolean swaped = true; //Variable en caso de que no haya intercambio
int i = 0;
int j = 0;
while (swaped) {
swaped = false;
i++;
while (j < result.size() - i - 1) {
//obtenemos los valores
Integer pos = result.get(j);
Integer next = result.get(j + 1);
//si la pos es mayor que el siguiente intercambia
if (pos > next) {
result.set(j, next);
result.set(j + 1, pos);
// swaped = true;
}
System.out.println(result);
j++;
}
}
return result;
}
Before :
[13, 7, 18, 5, 2]
[7, 13, 18, 5, 2]
[7, 13, 18, 5, 2]
[7, 13, 5, 18, 2]
After :
[7, 13, 5, 18, 2]
BUILD SUCCESSFUL (total time: 0 seconds)