Reputation:
I am trying to learn Bubble Sort algorithm. Most of the code on the internet are using Boolean variable, but I want to do this without Boolean.
# include <iostream>
using namespace std;
int main ()
{
int n;
int k;
int temp;
int arr[6] = {9,7,8,6,4,2};
for(n=0;n<6;n++){
for(k=0;k<n-1;k++){
if(arr[k]>arr[k+1]){
temp = arr[k+1];
arr[k+1]=arr[n];
arr[k] = temp;
}
}
}
for(n=0;n<6;n++){
cout<< arr[n] << endl;
}
}
Upvotes: 0
Views: 233
Reputation: 7496
Change your code to:
for(n=0;n<6;n++){
for(k=0;k<5;k++){
if(arr[k]>arr[k+1]){
temp = arr[k];
arr[k]=arr[k+1];
arr[k+1] = temp;
}
}
}
Your logic will never work because:
Upvotes: 3