I sorted an array using an algorithm and when I was going trough a book. The algorithm that I wrote had a name (BUBBLE SORT) . I was wondering if the program I roughly wrote implemented the bubble sort algorithm perfectly or is there a more efficient way of doing the same?
import java.util.Arrays;
public class Tool {
public static void main(String[] args){
int[] n = {4,8,12,87,32,98,12,45,94,42,938,84,63,67,86,37};
int inter = 0;
int arrayLength = n.length;
int pass = arrayLength-1;
for(int y = 0; y < arrayLength - 1; y++) {
for(int x = 0; x < pass; x++) {
if(n[x] < n[x + 1]) {
inter = n[x];
n[x] = n[x + 1];
n[x + 1] = inter;
num++;
}
}
pass--;
}
// To print the resulting array
System.out.println(Arrays.toString(n));
}
}
A good website to look for algorithm implementation is http://www.algolist.com. You can find the article on bubble sort here.
It looks like your code is lacking an optimization that checks if swapping is actually necessary (as Loki Astari noted).
This code is taken from the above URL, which implements this optimization:
You can read more about it from that page, it has helpful diagrams too if you’re more of a visual learner (like myself).
Cheers