【发布时间】: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