I am new to C language and I am currently learning to write a basic function of bubble sort. Everything seems good and the rest of the program runs well. However, there is an unexpected 0 appears in the output. I checked my code and I didn't know why. Could somebody help me? A Sample of input and output:
The orginal number set is: 23 12 17 8 5 46 75 19 11 4 The sorted number set is: 0 4 5 8 11 12 17 19 23 46
The code is :
// wirte a program of bubble sort
#include <stdio.h>
#include <string.h>
int main(void)
{
int num[10]; // a set to store10 numbers
int temp; //a temporary variable
int i,r,t,p,d; //counters
//store 10 numbers
for(i=0; i<10;++i)
{
printf("\nPlease enter the %dth number.\n",i+1);
scanf("%d",&num[i]);
}
printf("\n");
//display 10 numbers
printf("The orginal number set is:");
for(r=0; r<10; ++r)
{
printf("%5d",num[r]);
}
printf("\n");
//start to sort these numbers
for (p=0;p<10;++p)
{
for(t=0;t<10;++t)
{
if(num[t]>num[t+1])
{
temp=num[t];
num[t]=num[t+1];
num[t+1]=temp;
}
}
}
//print out the sorted set
printf("The sorted number set is:");
for(d=0;d<10;++d)
{
printf("%3d",num[d]);
}
printf("\n");
}
When you are comparing the values. You also compare the last one, with the first one outside the array. This happens to be 0(undefined behaviour,totally dependent on compiler) and gets switched in. The for-loop should become:
for (p=0;p<10;++p)
{
for(t=0;t<9;++t)
{
if(num[t]>num[t+1])
{
temp=num[t];
num[t]=num[t+1];
num[t+1]=temp;
}
}
}