开发者

Is this code a correct implementation of Bubble Sort?

开发者 https://www.devze.com 2023-02-24 06:47 出处:网络
I am used following bubble sort algorithm for making sorting . Is this algorithm correct? for (int a = itemWiseBidderList.size() - 1; a > 1; a--)

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).getRankIn开发者_如何学编程Int()) > (itemWiseBidderList.get(j + 1).getRankInInt()))
        {
           Collections.swap(itemWiseBidderList, j, j + 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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消