[英]C++ Bubble Sort Ascending order - does not sort all elements
我必須編寫一個程序,提示用戶輸入要讀取的整數。然后,它提示用戶輸入這些整數。 然后,它將整數存儲到向量中,並在氣泡排序過程中按升序打印排序后的值。 我程序中的問題是,向量中的所有值並非都正確排序。 這是我的代碼:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
int nums;
cout << "This program reads number of integers and store them into a vector."
<< "\nThen prints the values using Bubble Sort.";
cout << "\nEnter the size of the vector to be sorted using Bubble sort: ";
cin >> nums;
for (int i = 0; i < nums; i++)
{
int number;
cout << "Enter a number: ";
cin >> number;
numbers.push_back(number);
}
for (int i = 0; i < (nums - 1); i++)
{
for (i = 1; i < nums; ++i)
{
for (int j = 0; j < (nums - j); ++j)
if (numbers[j]>numbers[j + 1]) // swapping element in if statement
{
int number = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = number;
bool swap = true;
}
}
// Displaying the sorted list
cout << "\nSorted list in ascending order using Bubble Sort:\n";
for (int a = 0; a < nums; a++) //Use for loop to print the array
{
cout << numbers[a] << " ";
}
system("pause");
return 0;
}
}
例如,我輸入一個8整數長的向量,並輸入數字:43 6 23 1 75 34 98 76
輸出為:1 6 23 43 75 35 98 76
因此,看起來數字正確存儲到第5個整數的一半。
為了清楚起見,我制作了一個外部bubbleSort函數,下面是代碼。 希望它可以幫助您了解其工作原理。
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
void bubbleSort(vector<int>& arr)
{
int n = arr.size();
for(int i = 0; i < n-1; ++i)
{
for(int j = 0; j < n-i-1; ++j)
{
if(arr[j] > arr[j+1])
std::swap(arr[j], arr[j+1]);
}
}
}
int main()
{
int numOfElements;
cin >> numOfElements;
vector<int> arr(numOfElements);
for(int i = 0; i < numOfElements; ++i)
cin >> arr[i];
bubbleSort(arr);
for(auto elem : arr)
cout << elem << " ";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.