【发布时间】:2013-07-09 10:04:48
【问题描述】:
我执行了以下代码来检查冒泡排序和插入排序所需的迭代次数和交换次数。即使(参考下面的代码)与冒泡排序相比,插入排序实际上做了一半的迭代和相同数量的交换,但是为什么两者都具有相同的 BIG-O 复杂度
static void bubbleSortExample()
{
int iterationCount=0;
int swaps=0;
int [] arr={2,6,1,4,8,7,10,3};
int temp=0;
for(int i=0; i< arr.length; i++)
{
iterationCount=iterationCount+1;
for(int j=0; j<arr.length-1; j++)
{
iterationCount=iterationCount+1;
if(arr[j]> arr[j+1])
{
swaps= swaps+1;
temp= arr[j+1];
arr[j+1]= arr[j];
arr[j]= temp;
}
}
}
System.out.println("Bubble Sort----Iteration count are : " + iterationCount + " and swaps are : " + swaps);
}
//Bubble Sort Example Ends
//Insertion Sort Example Starts
static void insertionSortExample()
{
int iterationCount=0;
int swaps=0;
int [] arr={2,6,1,4,8,7,10,3};
for(int i=1;i< arr.length;i++)
{
iterationCount=iterationCount+1;
int key=arr[i];// this is the number that needs to be inserted in its correct position
for(int j=i-1; j >= 0; j--)
{
iterationCount=iterationCount+1;
if(key < arr[j])
{
swaps= swaps+1;
int t= arr[j];
arr[j]=key;
arr[j+1]=t;
}
}
}
System.out.println("Insertion Sort----Iteration count are : " + iterationCount + " and swaps are : " + swaps);
}
输出
Bubble Sort----Iteration count are : 64 and swaps are : 9
Insertion Sort----Iteration count are : 35 and swaps are : 9
【问题讨论】:
-
Big-O 描述了随着输入大小增加的行为。您的测试仅包含一个固定大小的数组,因此与 Big-O 分析无关。此外,在 Big-O 分析中忽略了常数因素,因此插入排序很有可能只执行“字面上一半”的操作,同时仍然具有与冒泡排序相同的 Big-O 复杂度。