我正在尝试计算选择排序中的交换次数和比较次数。 数组= [7,-9,-2,17,19,12,8,8,-20,15,3,5]。
void main()
{
int size = 12, arr[] = { 7, - 9, - 2, 17, 19, 12, 8, 1, - 20, 15, 3, 5 };
int i, j, temp;
int comparison = 0;
int swaps = 0;
std::cout << "Unsorted: ";
for (i = 0; i < size; i++)
{
std::cout << arr[i] << " ";
}
std::cout << "\n";
for (i = 0; i < size; i++)
{
for (j = i + 1; j < size; j++)
{
comparison = comparison + 1;
if (arr[i] > arr[j])
{
swaps = swaps + 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
std::cout << "\nComparisons: " << comparison;
std::cout << "\nSwap: " << swaps;
std::cout << "\n\nSorted: ";
for (i = 0; i < size; i++)
{
std::cout << arr[i] << " ";
}
这将返回66个比较和34个交换。如何正确计算和输出比较和交换的数量?
答案 0 :(得分:-1)
在这个很棒的网站http://bigocheatsheet.com/上,您可以找到所有不同排序算法的订单。它说选择排序应具有O(n ^ 2)的最坏情况。您有12个变量; 12 ^ 2 = 144,比您进行的交换和比较的数量要大得多-因此您处于最坏情况的范围之内。
但是,如果您说要输出已进行的交换,而不是交换的实际数量,则可以编写如下内容:
if (arr[i] > arr[j])
{
std::cout << "Swapping " << arr[i] << " with " << arr[j] << ".\n";
swaps = swaps + 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}