Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
chào các anh chị, các anh chị cho em hỏi 1 chút là tại sao lại
-
vòng lặp thứ nhất lại so sánh counter với length -1 mà không phải length
-
vòng lặp thứ 2 lại so sánh index với length -1 - counter
Chủ yếu là tại sao lại so sánh với length - 1 mà không phải là length thôi ạ.
Em cảm ơn rất nhiều ạ !!!
private static void bubbleSort(int[] unsortedArray, int length) {
int temp, counter, index;
for(counter=0; counter<length-1; counter++) { //Loop once for each element in the array.
for(index=0; index<length-1-counter; index++) { //Once for each element, minus the counter.
if(unsortedArray[index] > unsortedArray[index+1]) { //Test if need a swap or not.
temp = unsortedArray[index]; //These three lines just swap the two elements:
unsortedArray[index] = unsortedArray[index+1];
unsortedArray[index+1] = temp;
}
}
}
}
Tại mảng luôn có chỉ số bắt đầu là 0. Nên size của 1 mảng thì phải trừ đi 1 đơn vị để mới đúng số lượng element trong mảng. Cho nên với thuật toán sorting nổi bọt này thì chỗ loop for thứ 2 bạn cũng có thể suy ra vì sao nó dùng lun length-1-counter.