Hello. I have a doubt about this code
Code:
#include <stdio.h>
void bubble_sort(int []);
#define LEN 5
int main( void )
{
int array[LEN] = { 5 , 1 , 4 , 2 , 8 } , count =0 ;
printf(" Before sorting ");
for(; count<LEN; count++)
printf(" %d " , array[count]);
bubble_sort(array);
printf(" After sorting ");
count = 0;
while( count < LEN )
{
printf(" %d " , array[count]);
count++;
}
return 0;
}
void bubble_sort(int array[])
{
int i , j;
for( i = LEN - 1; i >= 1; i-- ) // <-------
{
printf("\n");
for(j=0; j<5; j++) // <-------
{
if( array[j] > array[j+1] )
{
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
printf("\n %d" , array[j]); // <----- print in every passing
}
}
return;
}
/*
Before sorting 5 1 4 2 8
1st passing ( 4 >= 1)
1
4
2
5
8
2nd passing ( 3 >= 1)
1
2
4
5
8
3rd passing ( 2 >= 1)
1
2
4
5
8
4th passing ( 1 >= 1)
1
2
4
5
8
After sorting 1 2 4 5 8
*/
I think the i>=1 it does one more passing that is unnecessary because the array is already sorted (after 3rd passing ).... I think i > 1 is the right. What is your opinion about that ? I had an argue with a friend about this.