尝试使用输入数字制作一个简单的数组排序器



我对C++甚至编码都很陌生。我试图制作一个简单的数组排序器,其中我首先输入数组中的元素数量,然后输入元素。我的结果应该是按升序排序的数组。我没有考虑过插入的元素是否相同的情况。所以我很想从你们那里得到一些帮助。 我面临的主要错误是只有第一个未排序的元素被排序,而其余的元素要么互换要么保持不变。

int main(){
int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];
for (int i = 0;i<x;i++){
cin>>A[i];
}
for(int i=0;i<x;i++)
cout<<A[i]<<",";


int count=0;

if(count <= (x-1)){
for (int i=0;i<(x-1);i++){
if(A[i]>A[i+1]){
int a;
a = A[i];
A[i] = A[(i+1)];
A[i+1] = a;
}
else if(A[i]<A[i+1]) 
count++;
}
}


cout<<"Sorted array:";
for(int i=0;i<x;i++)
cout<<A[i]<<",";
return 0;

}

你声明了一个可变长度数组

int x;
cout<<"Enter no. of elements"<<endl;
cin>>x;
int A[x];

因为它的大小不是编译时常量。

然而,可变长度数组不是标准的C++功能,尽管一些编译器有自己的语言扩展来支持可变长度数组,

最好使用类模板std::vector

另一个问题是,您似乎正在尝试使用气泡排序方法来对数组进行排序。但是这种方法需要两个循环。

这是一个演示程序,展示了如何实现气泡排序算法。

#include <iostream>
int main()
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << 'n';
for (size_t last = N, sorted = N; not ( last < 2 ); last = sorted)
{
for (size_t i = sorted = 1; i < last; i++)
{
if (a[i] < a[i - 1])
{
//  std::swap( a[i-1], a[i] );
int tmp = a[i - 1];
a[i - 1] = a[i];
a[i] = tmp;
sorted = i;
}
}
}
for (const auto &item : a)
{
std::cout << item << ' ';
}
std::cout << 'n';
}

程序输出为

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9

让我们尝试以下方法:

  • 找到数组中最大的元素,并通过与最后一个元素交换将其移动到末尾;

  • 对数组但最后一个元素重复此操作,依此类推。


要找到A[0..m-1]中最大的元素,请扫描数组并保留迄今为止最大的索引,让我们l此索引可以初始化为0

// Move the largest to the end
int l= 0;
for (int i= 1; i < m; i++)
{
if (A[i] > A[l]) l= i;
}
// A[l] is the largest in A[0..m-1]
Swap(A[l], A[m-1]);
// A[m-1] is the largest in A[0..m-1]

要排序,请按m递减重复。当子数组只包含一个元素时,您可以停止:

// Sort
for (int m= n-1; m > 1; m--)
{
// Move the largest to the end
....
}

编写Swap操作并组装整个代码是您的任务。还要检查

  • 极限情况Move的正确性m= 0, 1, 2.

  • 极限情况Sort的正确性n= 1, 2, 3.

  • 如何检测代码以验证Move是否完成其工作。

  • 如何检测代码以验证Sort是否完成其工作。

  • 键相等的情况下会发生什么。

可以稍微修复一下代码以使其正常工作。

只需将if (count <= (x - 1))替换为while (count < (x - 1)),并在循环开始时设置count = 0;,并将else if (A[i] < A[i + 1])替换为仅else。你的代码开始工作了!

我在下面的代码中进行了必要的修复。我还做了格式化(缩进和空格)以使代码看起来更好。其余的保持不变。

正如我所看到的,你有一种泡沫排序。

在线试用!

#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter no. of elements" << endl;
cin >> x;
int A[x];
for (int i = 0; i < x; i++) {
cin >> A[i];
}
for (int i = 0; i < x; i++)
cout << A[i] << ",";
int count = 0;
while (count < (x - 1)) {
count = 0;
for (int i = 0; i < (x - 1); i++) {
if (A[i] > A[i + 1]) {
int a;
a = A[i];
A[i] = A[(i + 1)];
A[i + 1] = a;
} else
count++;
}
}
cout << "Sorted array:";
for (int i = 0; i < x; i++)
cout << A[i] << ",";
return 0;
}

输入:

10
7 3 5 9 1 8 6 0 2 4

输出:

7,3,5,9,1,8,6,0,2,4,Sorted array:0,1,2,3,4,5,6,7,8,9,

如果你把数组的大小作为用户的输入,你必须在 c++ 中动态创建你的数组,比如 int *array=new int(x) 在获取元素的输入后,只需运行一个从 0 到 size 的嵌套循环,然后 从 0 到 size-1 的内部循环并检查 if(A[i]>A[i+1]) 如果为 true,则交换值,否则继续

最新更新