我做了以下代碼來檢查氣泡排序和插入排序所需的迭代次數和交換次數。儘管(指下面的代碼)插入排序做了字面上的一半迭代和相同數量的掉期相比,冒泡排序,然後怎麼來都具有相同的BIG-O複雜爲什麼氣泡排序和插入排序的性能相同,即O(n^2)
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分析無關。此外,在大O分析中忽略了常量因素,所以插入排序完全可能在操作次數上「完成一半」,而仍然具有與泡沫排序相同的Big-O複雜性。 – Mankarse