我正在编写一个程序来使用不同的算法对随机数进行排序。我已经创建了bubble_sort函数并运行了一个测试,它正确地对数字进行了排序,但我想检查函数中正在进行多少交换(交换)并将此数据返回给main。
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 100;
void random_fill(int numbers[], int size);
int bubble_sort(int numbers[], int size);
int main() {
int arr1[SIZE];
int arr2[SIZE];
random_fill(arr1, SIZE);
//cout << arr1[0] << endl;
//cout << arr1[1] << endl;
// Copy the array contents into arr2
for (int i = 0; i < SIZE; i++)
{
arr2[i] = arr1[i];
}
//cout << arr2[0] << endl;
//cout << arr2[1] << endl;
bubble_sort(arr2, SIZE);
for (int i = 0; i < SIZE; i++)
{
cout << arr2[i] << endl;
}
}
void random_fill(int numbers[], int size)
{
for (int i = 0; i < SIZE; i++)
{
numbers[i] = rand();
}
}
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int bubble_sort(int list_of_nums[], int size)
{
// We will make a series of passes through the list.
// On each pass through, we look at two numbers at a time.
// If the second number is bigger than the first number,
// swap the first and second number.
// Keep making passes through the list until no more swaps are made.
bool swap_was_made = true; // initialize to true so we can enter the loop
int swaps = 0;
while (swap_was_made)
{
// assume no swaps will happen on this pass
swap_was_made = false;
// Start at the beginning of the list (position 0)
// and start walking forward.
for (int i = 0; i < (size - 1); i++)
{
// Check two numbers at a time (positions 0 and 1),
// then 1 and 2, then 2 and 3, etc...)
if (list_of_nums[i] > list_of_nums[i + 1])
{
// If the first number in position i
// is bigger than the second number in position i + 1.
// And remember that we made a swap!
swap(list_of_nums[i], list_of_nums[i + 1]);
swap_was_made = true;
swaps++;
}
}
}
return swaps;
}
如果你能提供帮助,那就太好了。
答案 0 :(得分:3)
int bubble_sort(int list_of_nums[], int size)
{
...
return swaps;
}
你为什么遇到麻烦?您已经使bubble_sort
返回交换计数。
所以,只需存储它。
int swaps = bubble_sort(arr2, SIZE);