Hackerearth bubbleSort

时间:2017-11-06 17:19:46

标签: algorithm swap bubble-sort counting counting-sort

在Hackerearth,我尝试解决冒泡交换计数问题。并且我的输出总是与正确的输出不同。例如;
我的输出是2475,正确的输出是2788

#include <iostream>
using namespace std;


int main()
{
int *A,tm,times=0;
cin >> tm;
A = new int[tm];
for(int i = 0; i<tm;i++) {cin >> A[i];}

int temp;

for(int i = 0; i<tm;i++){
    for(int j = 0; j < tm-i-1;j++){
        if(A[j] > A[j+1]){
            times++;;
            temp = A[j];
            A[j] = A[j+1];
            A[j] = temp;
        }
    }
}
cout << times;

return 0;
}

我做错了什么或输出错误了吗?

2 个答案:

答案 0 :(得分:0)

在交换逻辑中,代替     A[j]=temp; 写     A[j+1]=temp;

在外部for循环中,i<tm-1代替i<tm

答案 1 :(得分:0)

可能这是无关紧要的,但可以找到具有更好复杂性的反演次数。该解决方案将需要 O(n ^ 2)。它可以在 O(nlogn)时间复杂度中完成。我们的想法是使用合并排序,并且在合并状态下,您已经知道有多少值来自值而不是实际计算它们的值。合并时,如果右子阵的值更大,那么它的所有其他值也更大。您只需要计算正确的值。这里提供了详细而愉快的解释。

相关问题