#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;
}
这是冒泡排序程序。我的查询是,如果我发现我的列表在任何中间点排序,我需要停止我的进程。我甚至做到了......但是这个程序仍然存在一些问题。它没有被门户网站接受,它触发了程序是“错误的答案”。我想在找到中间点时可能会出错。帮我解决这个问题..
答案 0 :(得分:1)
您可以设置一个标志并检查列表是否按如下方式排序:
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"
}
}
}
答案 1 :(得分:1)
#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;
}