繁体   English   中英

C-冒泡排序和插入排序的比较次数相同

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM