Java Bubble Sort Algorithm for Arrays
- DeTech Theory
- Jul 24, 2022
- 1 min read
In Java programming, Arrays are an essential data structure, but we often run into situations where we need to organize the elements. There are many different ways of sorting an Array, but the Bubble Sort algorithm is one of the most common and intuitive methods.
Bubble Sort uses nested for-loops to compare elements to one another. For each index in the array, if the subsequent indices are less than the value at the current index, the elements are swapped.
public static int[] bubbleSort(int[] ray){
int temp;
for(int i = 0; i<ray.length; i++){
for(int j = 0; j<ray.length-1; j++){
if(ray[j]>ray[j+1]){ //if true, then swap
temp=ray[j];
ray[j]=ray[j+1];
ray[j+1]= temp;
}
}
}
return ray;
}
And that's all there is to it!!
See you soon!
Bronwyn
nested for loop: a for-loop contained within another for-loop, allowing the program to run an iteration within another iteration.
Comments