Hackerearth泡泡排序 [英] Hackerearth bubbleSort

查看:84
本文介绍了Hackerearth泡泡排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Hackerearth中,我尝试解决冒泡排序交换计数。并且我的输出始终与正确输出不同。例如;

我的输出为2475,正确输出为2788

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?

推荐答案

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

A [j + 1] = temp;

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

在外部for循环, i< tm-1 而不是 i< tm

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

这篇关于Hackerearth泡泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆