About bubble sorting in C
This is my code:
//bubble sort
#include<stdio.h>
int main(){
int a[11];
int temp;
int i,j;
//input
for(i=1;i<=10;i++){
scanf("%d",&a[i]);
}
//sort
for(i=1;i<10;i++){ //the number of number
for(j=1;j<10-i;j++) //--
if(a[j]<a[j+i]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
//output
for(i=1;i<=10;i++){
printf("%d ",a[i]);
}
getchar();
getchar();
return 0;
}
The result was not what I expected. The input I used is 1 2 3 4 5 6 7 8 9 0, but after sorting the output is 8 6 5 4 3 7 2 9 1 0.
source to share
Note that arrays are null based - you have to run i = 0
on all instances - you only seem to need 10 numbers, so each iteration should be from 0..9
, and an array int a[10];
will suffice.
Assuming you want the bubblesort to be ordered from lowest to highest, the algorithm should be:
for(i=0; i < 10; i++){
for(j=0; j < 10 - i - 1; j++) // Because we are looking ahead one cell, -1
if(a[j] > a[j+1]){ // next cell
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
The value, after the first pass, the highest number will be in a[9]
. The next cycle will set the next high at a[8]
. and etc.
source to share