bubble sort

hi, I am making a program about bubble sort and my problem is the biggest number you entered becomes 0 in the process, can someone help me bout this,
this is my code:

void bubbleSort(int array[], int size ){

int numCompares = size - 1, ctr = 0;
int temp;
cout << "*** BUBBLE SORT PERFORMED ***\n" << endl;
while(numCompares != 0){
last = 1;
for(int i = 0; i <= numCompares; i++){

if( array [ i ] > array [ i + 1 ] ){

temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;

last = i;

}
}

numCompares = last - 1;
ctr++;
cout << "PASS " << ctr << endl;
print(ctr, numCompares + 1);

}

cout << "\nFINAL OUTPUT" << endl;
for(int i = 0; i < 10; i++){
cout << array[i] << " ";
}


}
Lets say that you sent in an array with 10 elements (int size = 10):

int numCompares = 9 (size -1)

for (int i = 0; i <= numCompares; i++) means i from 0 to 9

since i can be 9, lets see what happens in that case:
1
2
3
4
5
if (array [9] > array [10]) {
  temp = array[9];
  array[9] = array[10];
  array[10] = temp;
}


WHOA what did we just do? array[10] accesses the 11th member of the array, but there are only 10 elements that we meant to access. It means that we just swapped our largest value with some unknown value (in this case, 0).
Last edited on
Thank you so much for your help
i made it this way:

for(int i = 0; i <= numCompares; i++){

if( array [ i - 1 ] > array [ i ] ){

temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
}
}
Topic archived. No new replies allowed.