Hackerearth bubbleSort

只愿长相守 提交于 2019-12-11 14:08:41

问题


In Hackerearth i tried solving bubble sort swap counting. and my output always different from correct output.for example;
my output is 2475 and correct output is 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;
}

Am i doing something wrong or correct outputs are wrong?


回答1:


In the swap logic, in place of A[j]=temp; write A[j+1]=temp;

In the outer for loop, i<tm-1 instead of i<tm




回答2:


May be this is irrelevant, but it is possible to find the number of inversion with a better complexity. This solution will require O(n^2). It can be done in O(nlogn) time complexity. The idea is to use merge sort and at merging state you already know how many values are greater/smaller from a value without actually counting them. While merging, if a value of right subarray is greater, then all other values right of it are also greater. You just need to count how many values are at right. A detailed and pleasant explanation is provided here.

  • Number of swaps performed by Bubble-Sort on a given array
  • http://www.geeksforgeeks.org/counting-inversions/


来源:https://stackoverflow.com/questions/47142404/hackerearth-bubblesort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!