冒泡排序程序(错误输出)



//你好,我刚刚在写这个程序,我不明白为什么我的输出不能正确打印。答案应该是1、2、3、4、6,但它打印的却是2、1、4、3、6。非常感谢。

#include <iostream>
using namespace std;
void bubblesort(int A[], int n)
{
for (int i =1; i< n-1; i++)
{
for (int j =0; j< n-i-1; j++)
    {
if(A[i] > A[i+1])
        {
            swap(A[i], A[i+1]);
        }
    }
}
}
int main()
{
int A[] = {2,4,1,6,3};
bubblesort(A,5);
    for(int i =0; i<5; i++)
    {
        cout<<A[i]<<" ";
    }
}

您没有正确地编写外部循环,并与变量j交换,如下面的代码。

#include <iostream>
using namespace std;

//Bubble Sort 
void bubble_sort (int arr[], int n)
 {
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < n - i - 1; ++j)
      if (arr[j] > arr[j + 1])
     {
        int temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
  }     

//Driver Function
int main()
{
  int input_ar[] = {10, 50, 21, 2, 6, 66, 802, 75, 24, 170};
  int n = sizeof (input_ar) / sizeof (input_ar[0]);
  bubble_sort (input_ar, n);
  cout << "Sorted Array : " << endl; 
  for (int i = 0; i < n; ++i)
    cout << input_ar[i] << " ";
  return 0;
}

最新更新