In Introduction to programming with C++ 6th edition book, it explain the bubble sort algorithm with C++ and i understand it, but there is two lines of code I'm not understand why they in the code, when I tried to understand code I erase them and nothing changed and the algorithm still working. So I still confused about them. there is the code;
int main()
{
int numbers[4] = {23, 46, 12, 35};
int sub = 0; //keeps track of subscripts
int temp = 0; //variable used for swapping
int maxSub = 3; //maximum subscript
int lastSwap = 0; //position of last swap
char swap = 'Y'; //indicates if a swap was made
//repeat loop instructions as long as a swap was made
while (swap == 'Y')
{
swap = 'N'; //assume no swaps are necessary
sub = 0; //begin comparing with first
//array element
//compare adjacent array elements to determine
//compare adjacent array elements to determine
//whether a swap is necessary
while (sub < maxSub)
{
if (numbers[sub] > numbers[sub + 1])
{
//a swap is necessary
temp = numbers[sub];
numbers[sub] = numbers[sub + 1];
numbers[sub + 1] = temp;
swap = 'Y';
lastSwap = sub;
} //end if
sub += 1; //increment subscript
} //end while
maxSub = lastSwap; //reset maximum subscript
} //end while
//display sorted array
for (int x = 0; x < 4; x += 1)
cout << numbers[x] << endl;
//end for
system("pause");
return 0;
} //end of main function
so I don't understand lastSwap = sub
& maxSub = lastSwap
. are they important or I'm right about erase them from the code? can anyone explain to it to me.
Aucun commentaire:
Enregistrer un commentaire