c - Bubble sort doubts -


#include<stdio.h> #include<conio.h>  int main( ) {      int a[100];       int i, j, temp, n ;      printf("how many numbers want sort : \n");      scanf("%d",&n);      printf("enter %d number values want sort\n", n);      for(j=0; j<n; j++)      scanf("%d",&a[j]);       for(j=1;j<n;j++) 

how know above mentioned loop must repeated n times,how should 1 develop logic ,i know inner loop sort elements in list once,then why should repeat inner loop n times

     {           for(i=0; i<n; i++)           {                if(a[i]>a[i+1])                {                      temp=a[i];                      a[i]=a[i+1];                      a[i+1]=temp;                }            }      }       printf ( "\n\narray after sorting:\n") ;       ( = 0 ; <n ; i++ )      printf ( "%d\t", a[i] ) ;      getch();  } 

in internal loop find maximum. can't sure other numbers sorted.

other version (faster):

do (i = 0; < n-1; i++) do:   if a[i] > a[i+1]     swap(a[i], a[i+1])   end if end n = n-1 

while n > 1

(not checking maximum of previous loops)


Comments