如何计算冒泡排序中的交换

How to count swaps in bubble sort?

本文关键字:冒泡排序 交换 计算 何计算      更新时间:2023-10-16

我正试图编写一个程序,只计算多少交换和计算排序数组的校验和。然而,我不确定为什么计数器没有得到正确的掉期!我已经跟踪了很多次,这应该工作得很好。我错过了什么?

程序只输入正数作为数组的输入,要终止程序并显示交换,您应该输入"-1"

输入的简单示例:

1 4 3 2 6 5 -1

输出应该是

3

但输出根本不正确。

#include"stdafx.h"
#include <iostream>
using namespace std;
void bubble_sort(unsigned long long int arr[], int n)
{
    int swaps=0;
    for (int i = 0; i < n-1; ++i) {
        for (int j = 0; j < n - i - 1; ++j) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swaps++;
            }
        }
    }
    cout << "Swaps: " << swaps << endl;
}
int main() {
    int count=0;
    unsigned long long int  input_ar[1000];
    cout << "Enter the numbers: " << endl;
    for (int i = 0; i < 1000; i++) {
        cin >> input_ar[i];
        if (input_ar[i] == -1) {
            break;
        }
        count++;
    }
    bubble_sort(input_ar, count);
    return 0;
}

对于系列1 4 3 2 6 5,您首先交换43(一次交换),然后是42(两次交换),然后是65(三次交换)。这将留给您一个像1 3 2 4 5 6这样的数组,因此它仍然没有完全排序,您将进行另一次交换以将2置于正确的位置,从而导致四次交换(如果代码正常工作)。

删除上一个答案

你的程序工作正确;应该是4。为了使它工作,我取了unsigned long long并将其简单地转换为int。在swap变量变为增量之后添加以下代码,您将看到每次交换都准确地发生。

            cout << endl;
            cout << "Swap count: " << swaps << endl;
            cout << arr[j] << " is swapped with " << arr[j + 1] << endl;
            for (int a = 0; a < n; a++) {
                cout << arr[a] << " ";
            }
            cout << endl;

结果:

旧数组:1 4 3 2 6 5

Swap count 1:将3换成4;1 3 4 2 6 5

Swap count 2:将2换成4;1 3 2 4 6 5

Swap count 3:将5换成6;1 3 2 4 5 6

Swap count 4:2与3交换;1 2 3 4 5 6

互换:4

New array: 1 2 3 4 5 6

我建议下次你遇到问题时,你需要在特定的部分使用cout语句来确保程序正在做的事情是正确的。