问题描述
我必须编写一个包含10个整数的程序,然后显示它们。然后以相反的顺序显示它们。最后按升序显示它们。这是我到目前为止所拥有的。我停留在最后一部分(排序);其他一切都很好。
#include <iostream>
using namespace std;
int main(){
int a[10];
for (int i = 0; i < 10; i++)
{
cout << "Enter a number\n ";
cin >> a[i];
}
cout << "Array Reversed\n";
for (int i = 9; i >= 0; i--)
{
cout << a[i] << " ";
}
cout << "Numbers from lowest to highest\n";
for (int i = a[i]; i != 0; i = i/10 )
{
i % 10;
cout << i << " ";
}
}
解决方法
假设您需要冒泡排序,通常的想法是(伪代码):
# The array to sort.
arr = [3,1,4,5,9]
# Initially assume sorting needs a pass.
hasSwapped = true
while hasSwapped:
# If nothing swapped in this pass,we're done.
hasSwapped = false
# Check each element except last.
for idx = 0 to arr.sz - 2 inclusive:
# If bigger than next element,swap,flag another pass needed.
if arr[idx] > arr[idx + 1]:
temp = arr[idx]
arr[idx] = arr[idx + 1]
arr[idx + 1] = temp
hasSwapped = true
希望您应该能够从评论中了解意图,但基本思想是:
- 单次通过将检查所有元素,如果一个元素大于其后的元素,它将交换它们。
- 您必须至少进行一次 通过。
- 如果通过完成而没有交换,则数据将被排序。否则,需要更多通行证。
您现在的工作就是将其转换为您选择的语言。
我将在下面包括一个实现,该函数本身使用C语言(尽管它也可以在C ++中运行,如周围的测试工具所证明)。
但是,假设教育工作者不对他们给的作业进行窃检查是不明智的。换句话说,不要照原样使用此代码,几乎可以肯定您会被捕获。其目的只是向您展示可能的实现,您可以将自己的代码与以下内容进行比较:
#include <iostream>
using namespace std;
void bubbleSort(int *arr,size_t sz) {
int hasSwapped = 1;
while (hasSwapped) {
hasSwapped = 0;
for (size_t idx = 0; idx < sz - 1; ++idx) {
if (arr[idx] > arr[idx + 1]) {
int temp = arr[idx];
arr[idx] = arr[idx + 1];
arr[idx + 1] = temp;
hasSwapped = 1;
}
}
}
}
int main() {
int arr[] = { 3,9,2,6,3,9 };
for (size_t i = 0; i < sizeof(arr) / sizeof(*arr); ++i)
cout << arr[i] << ' ';
cout << '\n';
bubbleSort(arr,sizeof(arr) / sizeof(*arr));
for (size_t i = 0; i < sizeof(arr) / sizeof(*arr); ++i)
cout << arr[i] << ' ';
cout << '\n';
return 0;
}
输出符合预期:
3 1 4 1 5 9 2 6 5 3 5 9
1 1 2 3 3 4 5 5 5 6 9 9