Search code examples
algorithmswapbubble-sortcountingcounting-sort

Hackerearth bubbleSort


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?


Solution

  • 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