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

时间:2017-10-26 13:06:53

标签: c sorting

最近我正在做一个学校任务,要求我们编写一个程序来计算冒泡排序和插入排序的比较次数。

但是,当我执行程序时,它会为冒泡排序和插入排序返回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;
}

我想知道问题出在哪里?我该如何解决? 非常感谢。

2 个答案:

答案 0 :(得分:4)

比较次数 - 计划达到if次数的次数。 冒泡冒号 - if(x[j]>x[j+1])。 如果在while循环中插入排序 - (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;
}

答案 1 :(得分:0)

我根本没有看到任何奇怪的东西。它们都具有相同的时间复杂度,即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]);
        }
    }
相关问题