【问题标题】:Bubble sort the total number of comparisons and swaps冒泡排序比较和交换的总数
【发布时间】:2018-05-10 23:18:30
【问题描述】:

我有这段 C++ 冒泡排序代码。首先,它生成随机数并将它们放入一个数组中。之后,我调用我的 bubbleSort 函数,该函数进行排序。一切正常。但是我很好奇如何找到冒泡排序进行的一些总比较和数字交换? 我创建了一个 CountBubbleSort 整数进行比较。但是我不确定我应该在代码的哪一部分增加它。我想在第二个 for 循环之后添加它,在第一个循环内。希望你明白我的意思。是对还是错?比较次数定义了这个公式 n*(n-1))/2。使用交换它是 3*(n-1)。但是我怎样才能将它实现到我的代码中呢?谢谢大家的帮助。

void swap(double *xp, double *yp)
{
    double temp = *xp;
    *xp = *yp;
    *yp = temp;
}

double *Data;
double* A;
double n, temp;

void generate(int _n, const char *_file);
void read(const char *_file);   
void printArray(double arr[], int n); 
void bubbleSort(double arr[], int n);

int main()
{
    int m;
    int CountBubbleSort = 0;

    srand(time(NULL));
    cout << "Amount of random numbers you want: ";
    cin >> m;
    cout << "Generating random data ..." << endl;
    generate(m, "duom.txt");
    cout << "Reading data" << endl;
    read("duom.txt");
    A = new double[n];

    for (int i = 0; i < n; i++) {
        A[i] = Data[i];
    }

    cout << "Randomly generated array" << endl;
    printArray(A, n);

    // Bubble Sort
    bubbleSort(A, n);

    cout << "Array after bubble sort" << endl;
    printArray(A, n);

    return 0;
}

void bubbleSort(double arr[], int n)
{
    bool swapped;
    for (int i = 0; i < n - 1; i++)
    {
        swapped = false;
        for (int j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                swap(&arr[j], &arr[j + 1]);
                swapped = true;
            }
        }
        // Should I add CountBubbleSort += i here or not?
        if (swapped == false)
            break;
    }
}

void printArray(double arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << A[i] << endl;
    }
}

【问题讨论】:

    标签: c++ sorting bubble-sort


    【解决方案1】:

    这是一个相对简单的变化:

    • if 语句之前增加比较计数
    • if 语句中增加交换计数器

    取两个int&amp;参数进行计数,像这样:

    void bubbleSortCounted(double arr[], int n, int& countComparisons, int& countSwaps);
    

    递增计数器的代码如下所示:

    countComparisons++;
    if (arr[j] > arr[j + 1])
    {
        countSwaps++;
        swap(&arr[j], &arr[j + 1]);
        swapped = true;
    }
    

    来自main() 的调用如下所示:

    int cmp = 0, swp = 0;
    bubbleSort(A, n, cmp, swp);
    std::cout << cmp << " comparisons, " << swp << " swaps" << std::endl;
    

    【讨论】:

      【解决方案2】:

      但是我很好奇如何找到冒泡排序进行的总比较和数字交换?我创建了一个 CountBubbleSort 整数进行比较。但是我不确定我应该在代码的哪一部分增加它。

      您的bubbleSort() 函数中只有一行您实际比较了数组中的两个元素,因此如果您想计算比较元素的次数,您应该在之前立即增加计数器或在比较发生后立即。

      【讨论】:

      • 是的,但不要相信我的话:在一个小列表上尝试它并确保获得预期的比较次数,或者在调试器中逐步执行代码并确认每次比较两个元素时计数器都会递增。
      • 感谢您的帮助:)
      猜你喜欢
      • 2018-10-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      • 1970-01-01
      相关资源
      最近更新 更多