我的bubbleSort没有按正确的顺序打印

问题描述 投票:0回答:1

如果你运行这个程序,它似乎有效。但是,而不是按升序打印:

(0-15)

它打印:

1-2-3-4-5-6-7-8-9-0-10-11-12-13-14-15

零应该在程序的开头,但是在9到10之间。请运行代码,因为我不知道有什么问题。

#include <iostream>
#include <utility>

using namespace std;

int main()
{

int arr[] = { 2,1,3,5,4,7,6,9,8,10,0,12,11,14,15,13 };
int n = sizeof(arr) / 4;

int counter = -1;

while(counter != 0)
{

    if (counter != 0)
    {
        counter = 0;
    }

    for (int i = 0; i < n - 1; i++)
    {
        if (arr[i] > arr[i + 1])
        {
            swap(arr[i], arr[i + 1]);
            counter++;
        }
    }

    if (counter > 0)
    {
        counter = 0;
    }
    else if (counter == 0)
    {
        return 0;
    }
}

for (int j = 0; j < n; j++)
{
    cout << arr[j] << " " << endl;
}

system("Pause");

}
bubble-sort
1个回答
0
投票

你只需经​​过一次冒泡排序循环,因为你在内循环之后将counter设置为零,因此立即退出外循环。另外,为什么你在循环中有一个return 0

#include <algorithm>
#include <iostream>

int main ()
{   
    int arr[] = {2, 1, 3, 5, 4, 7, 6, 9, 8, 10, 0, 12, 11, 14, 15, 13};
    int n = sizeof (arr) / 4;

    int counter = -1;

    while (counter != 0)
    {
        counter = 0;

        for (int i = 0; i < n - 1; i++)
        {
            if (arr[i] > arr[i + 1])
            {
                 std::swap (arr[i], arr[i + 1]);
                 counter++;
            }
        }
    }   

    for (int j = 0; j < n; j++)
    {
         std::cout << arr[j] << " " << endl;
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.