Search code examples
arrayssortingbubble-sort

Time limit exceeded in bubble sort


Problem-To sort array in ascending order
Algorithm used-Bubble sort
Error-Time limit exceeded
Compiler-ideone online editor /Codeblocks What could be the possible alternative for this?

int a[5];
int i,t,j;
for(i=0;i<=4;i++)  //for initialising the elements
 {
 printf("Enter 5 numbers");
 scanf("%d",&a[i]);
 }

for(j=0;j<5;i++)  //for sorting 
{

  for(i=0;i<5;i++)
  {
  if(a[i]>a[i+1])
    {
  t=a[i+1];
  a[i+1]=a[i];
  a[i]=t;
    }
  }
 }
for(i=0;i<=4;i++)  //for printing the sorted array
{

   printf("%d\n",a[i]);
}

Solution

    • Your loop:

      for(j=0;j<5;i++)  //for sorting
      

    should say j++, so it should be

        for(j=0;j<5;j++) 
    
    • Your second loop:

      for(i=0;i<5;i++)
      

    should be

        for(i=0;i<4;i++)