snippetjavaMinor
Bubble Sort implementation in Java
Viewed 0 times
sortbubbleimplementationjava
Problem
I want to know if there is any other better way to write this algorithm. What other data structures could be used to make it more simple and effective?
Output:
public class BubbleSort {
public static void bubbleSort(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i array[k]) {
swapNumbers(i, k, array);
}
}
printNumbers(array);
}
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
public static void main(String[] args) {
int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
bubbleSort(input);
}
}Output:
2, 4, 6, 9, 12, 23, 0, 1, 34,
2, 4, 6, 9, 12, 0, 1, 23, 34,
2, 4, 6, 9, 0, 1, 12, 23, 34,
2, 4, 6, 0, 1, 9, 12, 23, 34,
2, 4, 0, 1, 6, 9, 12, 23, 34,
2, 0, 1, 4, 6, 9, 12, 23, 34,
0, 1, 2, 4, 6, 9, 12, 23, 34,
0, 1, 2, 4, 6, 9, 12, 23, 34,
0, 1, 2, 4, 6, 9, 12, 23, 34,
0, 1, 2, 4, 6, 9, 12, 23, 34Solution
Efficiency
Style
Looking Forward
Right now, it's difficult to reuse
If you want to be able to debug it in the future, then put it behind a debugging flag:
- As someone else mentioned, the inner loop only needs to run up to
m-1.
- The standard optimization is that if an entire inner loop runs without ever swapping, then the array is now sorted and you can quit early. Notice how it prints the same thing the last 4 times.
Style
- If you've done bullet point 1 above, the only usage of
nwill befor (int m = n..., so you can just replace that with its definition and get rid ofint n = array.length;above.
- You don't need to declare 'int k;' at the top, Java is smart enough to make that optimization. You can just use
int k = i + 1;.
- In
swapNumbers, combine the first two lines intoint temp = array[i];
Looking Forward
Right now, it's difficult to reuse
bubbleSort because it spews output to the console. I get that you want to see what it's doing, but once it's working you should take that out. The sort function should only be responsible for sorting; the user of the function (in this case, the main method) can decide what to do with the results (e.g., print them).If you want to be able to debug it in the future, then put it behind a debugging flag:
// this goes top-level in the BubbleSort class:
private static final boolean DEBUG = false;
// then, inside bubbleSort:
if (DEBUG)
printNumbers(array);Code Snippets
// this goes top-level in the BubbleSort class:
private static final boolean DEBUG = false;
// then, inside bubbleSort:
if (DEBUG)
printNumbers(array);Context
StackExchange Code Review Q#109647, answer score: 3
Revisions (0)
No revisions yet.