the improved BubbleSort.

来源:互联网 发布:unity 2d 不会编程 编辑:程序博客网 时间:2024/06/14 20:39

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;
    }
}

0 0
原创粉丝点击