我做了下面的代码来检查冒泡排序和插入排序所需的迭代次数和交换次数。即使(参考下面的代码)与冒泡排序相比,插入排序实际上做了一半的迭代和相同数量的交换,但是为什么两者都具有相同的 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