问题
I am used following bubble sort algorithm for making sorting . Is this algorithm correct?
for (int a = itemWiseBidderList.size() - 1; a > 1; a--)
{
for (int j = 0; j < a; j++)
{
if ((itemWiseBidderList.get(j).getRankInInt()) > (itemWiseBidderList.get(j + 1).getRankInInt()))
{
Collections.swap(itemWiseBidderList, j, j + 1);
}
}
}
回答1:
If bubble sorting is not a requirement (by homework?), then the correct way to implement sorting in Java is by calling
Collections.sort(itemWiseBidderList);
If your list items implement Comparable
, or
Collections.sort(itemWiseBidderList, new Comparator() {
public int compare(Object o1, Object o2) {
// Compare o1, o2 .getRankInInt() here
}
});
This will be a lot faster than bubble sorting.
回答2:
This is pseudo-code, you can verify if your code is correct:
procedure bubbleSort( A : list of sortable items )
n = length(A)
for (i = 0; i < n; i++)
/* back through the area bringing smallest remaining element to position i */
for (j = n-1; j > i; j--)
if A[j-1] > A[j] then
swap(A[j-1], A[j])
end if
end for
end for
end procedure
source from wikipedia
回答3:
It does seem to be correct (though I did NOT test it), however Collection
is supposed to be comparable so you should probably just call itemWiseBidderList.sort()
.
What datatype is itemWiseBidderList
?
来源:https://stackoverflow.com/questions/5619722/is-this-code-a-correct-implementation-of-bubble-sort