c++:排序数组又名尝试修复选择排序

c++: Sorted array AKA trying to fix the Selection Sort

本文关键字:排序 选择 数组 c++      更新时间:2023-10-16

所以我尝试做这个选择排序方法,该方法读取您的数组并将其从大到最少显示

" 这些是未排序的数组 29315

这些是排序数组 95321 ">

问题是当我要求用户"输入数组的大小"时,如果我输入 6,我只能输入 5 个数字而不是 6,就像上面的例子一样。我在函数或 For 循环中面临的问题是什么,阻止我输入第 6 个数字

PS:我试图想象代码以制作动态数组然后排序。我该怎么做?正如您在下面看到的,我让用户输入自己的数组,但限制为 n AKA 1000。请问我怎样才能解决这个问题。谢谢

#include <iostream>
using namespace std;
void SelectionSort(int *a, int k);
int main()
{
int j = 0;
int n = 1000; //limit of array
int k = 0; //number of array enters

cout << "please enter length of array" << endl;
cin >> k;
int *a = new int[n];
//int a[k];
for (int i = 0; i < k - 1; i++)
{
cout << "please enter the number in the array please" << endl;
cin >> j;
a[i] = j;
}
cout << "these are the unsorted array" << endl;
for (int i = 0; i < k -1; i++){
cout << a[i];
}
cout << endl;
SelectionSort(a, k);
cout << "these are the sorted array" << endl;
for (int i = 0; i < k -1; i++){
cout << a[i];
}
return 0;
}
//function
void SelectionSort(int *a, int k){
for (int i = 0; i < k - 1; i++){
int maxIndex = i;
for (int j = (i + 1); j < k; j++)
{
if (a[j] > a[maxIndex])
{
maxIndex = j;
}
}
int temp = a[i];
a[i] = a[maxIndex];
a[maxIndex] = temp;
}
}

问题是当我要求用户"输入数组的大小"时 如果我输入 6,我只能输入 5 个数字而不是 6 个

for (int i = 0; i < k - 1; i++)

假设您在此处输入 6,此循环将从 0 运行到 4,即 FIVE 次。因此,您只能输入五个数字

您可以像下面这样修改此循环:

for (int i = 0; i < k; i++)

PS:我试图想象代码以制作动态数组然后排序。我该怎么做?正如您在下面看到的,我让用户输入自己的数组,但限制为 n AKA 1000。请问我怎样才能解决这个问题。谢谢

您的要求不明确。请再次陈述您的问题。正如评论中提到的,我认为没有必要n.您可以要求用户输入数组所需的元素数量,即k然后您可以动态地为如此多的整数分配空间,如下所示:

int *a = new int[k];