起泡算法的最佳复杂度O(N)

//起泡法,大数沉底

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
	char a[1000];
	gets(a);
	int k=strlen(a);
	for(int i=0;i<k-1;i++)//趟
	{
		for(int j=0;j<k-1-i;j++)//比较次数:k-i
		{
			 if(a[j]>a[j+1])
			 {
				char temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			 }
		printf("%s \n",a);
		}
		printf(" \n");
	}
	printf("%s",a);
 system("pause");
return 0;
}




引用:

冒泡排序最佳情况的时间复杂度,为什么是O(n)

http://www.cnblogs.com/melon-h/archive/2012/09/20/2694941.html


  可是网上和许多书上都写道是O(n),不知是否有人能帮我解答一下呢?

  2.4 在Stackoverflow上问到答案了。

  我原本的代码的时间复杂度确实应该是O(n^2),但算法可以改进,使最佳情况时为O(n)。改进后的代码为:

复制代码
public void bubbleSort(int arr[]) {
    boolean didSwap;
    for(int i = 0, len = arr.length; i < len - 1; i++) {
        didSwap = false;
        for(int j = 0; j < len - i - 1; j++) {
            if(arr[j + 1] < arr[j]) {
                swap(arr, j, j + 1);
                didSwap = true;
            }
        }
        if(didSwap == false)
            return;
    }    
}
复制代码


猜你喜欢

转载自blog.csdn.net/qqyuanhao163/article/details/48196675