我已经尝试过以我能想到的每一种方式实现bubbleSort算法,但它仍然只排序第一个数字。我不明白为什么会这样。任何见解都会很有帮助!我试着***请注意,我必须排序数组(因此在实现中不能使用vector)。
bubbleSort.h
#ifndef BUBBLE_SORT_
#define BUBBLE_SORT_
#include <cstddef>
#include <iostream>
#include <array>
using std::size_t;
// void displayBag(ArrayBag &bag);
void bubbleSort(int arr[], size_t n);
#endif
bubbleSort.cpp
#include "bubbleSort.h"
#include <iostream>
#include <cstddef>
#include <array>
#include <vector>
using std::cout; using std::endl; using std::vector; using std::size_t;
/****************************************************************************/
/* Function: bubbleSort
/* Inputs: n = num of elements in arr
arr = arr to be sorted
/* Outputs: outputs sorted arr to console
/* Purpose: This function sorts arr in ascending order
/****************************************************************************/
void bubbleSort(int arr[], size_t n)
{
int i = 0;
int j = 0;
for(i; i < n; i++)
{
for(j; j < (n-1); j++)
{
if (arr[j] > arr[j+1])
{
{
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
}
}
main.cpp
#include "bubbleSort.h"
#include "bubbleSort.cpp"
#include <cstddef>
#include <iostream>
#include <array>
using std::cout; using std::endl;
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
size_t n = sizeof (arr) / sizeof (int);
cout << "The array has " << n << " elements." << endl;
bubbleSort(arr, n);
printf("Sorted array: n");
for (int i=0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
-
在第一个外部循环之后,
j
的值已经是n-1
,因此内部循环不会运行。 -
在每个外循环之后,最后的
i
元素被排序,所以它应该是for (j = 0; j < (n-i-1); j++)
为两件事更新循环:
- 为每次运行初始化内部循环
- 要优化循环,执行(n - i - 1)