나는이 자격 증명을 사용하여 작동합니다 버블 선택 방법, 코딩 해요 :아웃 [ArrayList에와 버블 선택]
/* Write code for a Bubble Sort algorithm that starts at the right side of
* of ArrayList of Comparable objects and "bubbles" the largest item to the
* left of the list. The result should be an ArrayList arranged in descending
* order.
*/
@SuppressWarnings("unchecked")
void bubbleSort(ArrayList <Comparable> list) {
int end = list.size();
for (int i = 0 ; i < end; i++){
for (int j = end; j > 0; j--){
if (list.get(j).compareTo(list.get(j-1)) > 0){
//swap
Comparable temp = list.get(j);
list.set(j,list.get(j - 1));
list.set(j - 1, temp);
//System.out.println(list);
}
}
end--;
}
}
문제는이다, 자바는 그것을 밖으로 나에게 말할 것이다 경계.
내가 대신 그러나 그것은 완전히 (이것은 앞서 한 루프를 중지 일명) 정렬 완료 할 목록을 실행하는 데 필요한 횟수를 실행하지 않습니다,
for (int j = end - 1; j > 0; j--)
코드가 다음 실행
를 사용하는 경우
내부 루프에는 N 개의 객체가 있고 필요에 따라 각각을 이전과 비교하기 때문에 첫 번째 객체에는 이전 객체가 없으므로 N-1 검사를해야합니다 . 'for (int j = end - 1; j> 0; j -)가 맞습니다. – aalku
내 편집을 확인하십시오 – kai