That algorithm appears to ignore "asc". Try this:
public static void bubbleSort(int[] a, boolean asc) {
for (int i=0; i
for (int j=i+1; j
if ((a[j] > a[i]) ^ asc) {
int t = a[i];
a[i] = a[j];
a[j] = t;
} } } }
=====================
Notes:
(1) I use the exclusive-or operation ("^") with 'asc' and a reversed compare with a[i] and a[j]. When asc is true, this inverts the result of the compare (ascending), and when false, it leaves the result of the compare alone (descending).
(2) Note that I *DON'T* use the multiple additions to swap. While it may "look cool" to not use an additional variable, I believe it is stylistically not a good idea:
(a) It's less efficient: 3 additions AND 3 assignments AND 9 array dereferences in the swap-by add, versus just 3 assignments and 4 array dereferences and no additions in my implementation.
(b) It's less apparent what's going on, and this makes the code harder to maintain. It is a good habit to get in the practice of writing code that a someone other than yourself can review, understand, and easily work on.
(c) Adding integers which are very close to the positive or negative limit for integer values, can break down. (In this case, I don't think it does, but why overflow an int unnecessarily?)
========================
Sample main() and test:
public static void main(String[] args) {
int a[] = new int[] { 5, 6, 7, 4, 1 };
// test ascending
bubbleSort(a, true);
for (int i=0; i
System.out.print("" + a[i] + " ");
System.out.println(" [asc]");
// test descending
bubbleSort(a, false);
for (int i=0; i
System.out.print("" + a[i] + " ");
System.out.println(" [desc]");
}
-------------------
Output:
1 4 5 6 7 [asc]
7 6 5 4 1 [desc]
2007-08-09 11:49:54
·
answer #1
·
answered by McFate 7
·
0⤊
0⤋
public static void bubbleSort(int[] a , boolean asc)
{
int i;
for (i = 0 ; i < a.length - 2; i++){
for (j = i + 1 ; j < a.length-1; j++){
if (a[ j ] < a[ i ]) {
a[ i ] = a[ j ] + a[ i ];
a[ j ] = a[ i ] - a[ j ];
a[ i ] = a[ i ] - a[ j ];
}
}
}
}
If you haven't seen this before:
a[ i ] = a[ j ] + a[ i ];
a[ j ] = a[ i ] - a[ j ];
a[ i ] = a[ i ] - a[ j ];
It's the classic way to swap 2 integers without using a temporary variable.
What you will have to do is reverse the logic depending on the boolean asc which is saying ascending or descending order.
2007-08-09 11:07:51
·
answer #2
·
answered by E.M.Bed 5
·
0⤊
0⤋