如何计算冒泡排序中的交换
How to count swaps in bubble sort?
我正试图编写一个程序,只计算多少交换和计算排序数组的校验和。然而,我不确定为什么计数器没有得到正确的掉期!我已经跟踪了很多次,这应该工作得很好。我错过了什么?
程序只输入正数作为数组的输入,要终止程序并显示交换,您应该输入"-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
,您首先交换4
和3
(一次交换),然后是4
和2
(两次交换),然后是6
和5
(三次交换)。这将留给您一个像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语句来确保程序正在做的事情是正确的。
相关文章:
- 如何在C++中对数组进行冒泡排序
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 在C++中使用冒泡排序时出现意外值
- 冒泡排序中所需的交换次数,而无需实际对其进行排序
- 如何对文件中数组中的单个列进行冒泡排序?C++
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 冒泡排序无法对C++中的对象的动态数组进行排序
- 冒泡排序.C++
- 链表的冒泡排序
- 有没有选择排序优于冒泡排序的输入
- C++:如何使用冒泡排序来重新排列我的数据
- 冒泡排序随机数
- 矢量下标超出范围-冒泡排序
- 使用冒泡排序比较类对象
- 在c++中使用冒泡排序/交换对字符串进行排序
- 矢量下标超出范围错误,C++,冒泡排序
- 在不进行冒泡排序的情况下,计算数组中冒泡排序交换的次数
- 使用交换函数和指针的c++冒泡排序
- 冒泡排序使用幻灯片而不是交换
- 如何计算冒泡排序中的交换