How to stop my process if I find the list in sorted in any intermediate point-IN BUBBLE SORT?

匿名 (未验证) 提交于 2019-12-03 01:03:01

问题:

#inlcude<stdio.h> int main() {  int arr[30],num,i,j,k,temp,l=0;  printf("Enter the number of elements :\n");  scanf("%d",&num);  for(i=1;i<=num;i++)  {    printf("Enter element %d\n",i);    scanf("%d",&arr[i]);  } for(k=1;k<=num;k++) {if(arr[k]>arr[k+1])   l++;}  if(l!=0)  {     for(i=2;i<=num;i++)  {l=0;    for(k=1;k<=num;k++)    {      if(arr[k]>arrk+1])      l++;}    if(l!=0)    {for(j=1;j<num;j++)     {      if(arr[j]>arr[j+1])      {        temp=arr[j];        arr[j]=arr[j+1];        arr[j+1]=temp;      }     }   printf("\nAfter pass %d elements are:",i-1);   for(k=1;k<=num;k++)      printf("%d",arr[k]);}   else      break;      }   }   printf("\nsorted list is:\n");   for(k=1;k<=num;k++)      printf("%d ",arr[k]);    retrun 0;  }

This is the Bubble sort program. My query is I need to stop my process if I find my list is sorted in any intermediate point. I even did that... But still there is some problem with this program. It's not getting accepted in portal, It triggers as the program is "Wrong Answer". I guess there may be mistakes in finding out the intermediate point. Help me out to figure out this..

回答1:

You can set a flag and check if the list is sorted like this:

for(i=0; i ...... { flag=1; // We are setting a "break point" here by setting flag=1; If any exchange of elements take place inside if loop, flag will be //set back to zero inside the if block statements. for(j=0; j ...... { if (a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; flag=0; // flag is set back to zero because there occured an "exchange of element" } } }


回答2:

#include<stdio.h> int main()  {   int array[100],i,n,c,swap,flag=0;   printf("Enter the number of elements :\n");   scanf("%d",&n);   for(c=0;c<n;c++)   {   printf("Enter element %d\n",c+1);   scanf("%d",&array[c]);   }   printf("Unsorted list is :\n");   for(i=0;i<n;i++)     printf("%d ",array[i]);   printf("\n");   for(c=0;c<n-1;c++)   {     if(flag==0)     {       flag=1;      for(i=0;i<n-1;i++)      {          if(array[i]>array[i+1])         {           swap=array[i];           array[i]=array[i+1];           array[i+1]=swap;           flag=0;         }     }     printf("After Pass %d elements are :",c+1);     for(i=0;i<n;i++)     {       printf("%d ",array[i]);     }                        printf("\n");     }   }   printf("Sorted list is :\n");   for(c=0;c<n;c++)     printf("%d ",array[c]);   return 0; }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!