Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
m (→{{header|Java}}: Fixed it again) |
|||
Line 843: | Line 843: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type: |
Bubble sorting (ascending) an array of any <tt>Comparable</tt> type: |
||
<lang java>public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { |
|||
boolean changed = false; |
|||
do { |
|||
do { |
|||
changed = false; |
|||
for (int a = 0; a < comparable.length - 1; a++) { |
|||
for (int a = 0; a < comparable.length - 1; a++) { |
|||
if (comparable[a].compareTo(comparable[a + 1]) > 0) { |
|||
E tmp = comparable[a]; |
|||
comparable[a + 1] |
comparable[a] = comparable[a + 1]; |
||
comparable[a + 1] = tmp; |
|||
changed = true; |
|||
} |
|||
} |
} |
||
} |
} while (changed); |
||
} |
}</lang> |
||
For descending, simply switch the direction of comparison: |
For descending, simply switch the direction of comparison: |