您的位置:首页 > 其它

the improved BubbleSort.

2015-01-15 09:58 567 查看
the bubble sort is easy to use,but the effiency is pretty low.How we solve the problem?

when we use bubble sort,we know when we sort the data again and again,it seems that there is a status that the sort has already sorted,but we also scan the data,so,it is an abuse.In order to make it more efficient,we can use
a flag to judge the scanner's status,if the scanner is still working.we continue the process of scan.While the scanner is stop,we can make the flag into 1 status,so we can jump out through the circulation.the method is very famous:more space instead of time.the
following is the realization.

void bubblesort(int a[],int n)

{

    int i,j,flag=0,r;

    for(i=0;i<n-1;i++)

    {

        for(j=n-1;j>i;j--)

        {

            if(a[j]<a[j-1])

            {

                r=a[j-1];

                a[j-1]=a[j];

                a[j]=r;

                flag = 1;//there has the exchange of data

            }

        }

        if(flag = 0)

            break;

        else

            flag = 0;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: