[英]C - Same number of number of comparisons for bubble sort and insertion sort
最近,我正在執行一項學校任務,要求我們編寫一個程序以對冒泡排序和插入排序的比較次數進行計數。
但是,當我執行程序時,它會為冒泡排序和插入排序返回2個相同的值。
例:
Sorted!
Number of comparison for bubble sort: 559150
Number of comparison for insertion sort: 559150
這是我的程序:
#include<stdio.h>
#include<time.h>
#define SIZE 1500
void swap(int *a,int *b) //swap function
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int bubblesort(int x[]) //Bubble sort
{
int i,j;
int count = 0;
for(i=0;i<SIZE-1;i++)
{
for(j=0;j<SIZE-i-1;j++)
{
if(x[j]>x[j+1])
{
swap(&x[j],&x[j+1]);
count = count + 1; //count comparison
}
}
}
return count;
}
int insertionsort(int x[]) //Insertion sort
{
int i,j,temp;
int count = 0;
for(i=1;i<SIZE;i++)
{
temp = x[i];
j = i-1;
while((j>=0)&&(x[j]>temp))
{
count = count + 1; //count comparison
x[j+1] = x[j];
j--;
}
x[j+1] = temp;
}
return count;
}
int main()
{
int i;
int b_array[SIZE];
int i_array[SIZE];
int b_count = 0;
int i_count = 0;
srand(time(NULL));
for(i=0;i<SIZE;i++) //Generate random number and assign it the the array
{
b_array[i] = rand()%SIZE;
i_array[i] = b_array[i];
}
b_count = bubblesort(b_array);
i_count = insertionsort(i_array);
printf("Sorted!\n");
printf("Number of comparison for bubble sort: %d\n",b_count);
printf("Number of comparison for insertion sort: %d",i_count);
return 0;
}
我想知道問題出在哪里? 以及我該如何解決? 非常感謝。
比較的數量-多少次方案達成if
語句。 對於冒泡排序-if if(x[j]>x[j+1])
。 在插入排序的情況下(x[j]>temp)
循環中的(x[j]>temp)
。 因此,您是在計算掉期數而不是比較數。
int bubblesort(int x[])
{
int i,j;
int count = 0;
for(i=0;i<SIZE-1;i++)
{
for(j=0;j<SIZE-i-1;j++)
{
count++; //comparison. Increment "count" each time program reach "if"
if(x[j]>x[j+1])
{
swap(&x[j],&x[j+1]);
}
}
}
return count;
}
我一點都沒有發現任何奇怪的地方。 它們都具有相同的時間復雜度,即O(n²)。 他們也有O(n²)比較。 除了。 如果您分析冒泡排序和插入排序(沒有二進制搜索的變體,這是您正在使用的變體),您會發現它們非常相似。
但是,當我查看您的代碼時,您不算比較。 您數掉期。
for(j=0;j<SIZE-i-1;j++) {
// Move it outside the comparison
count = count + 1; //count comparison
if(x[j]>x[j+1]) {
swap(&x[j],&x[j+1]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.