c++:排序数组又名尝试修复选择排序
c++: Sorted array AKA trying to fix the Selection Sort
所以我尝试做这个选择排序方法,该方法读取您的数组并将其从大到最少显示
" 这些是未排序的数组 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];
相关文章:
- C++选择排序算法中的逻辑错误
- 高级选择排序 - 在一次迭代中搜索两个元素
- 选择排序C++(已修改)并非适用于所有情况
- C++选择要作为排序依据的属性
- C++为什么我的指针选择排序中存在分段错误?
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 快速排序 - 三个中位数枢轴选择 - 某些元素顺序不正确
- 选择排序时交换函数调用的数量和完成的交换次数是否相同?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 使用选择排序对数组数据结构进行排序,但它不起作用
- c++ 选择排序在特定情况下不起作用
- 修改的选择排序,选择最大的数字,然后交换到最后
- 如何选择排序一些结构
- 选择排序以查找未排序数组中的最大数字
- 选择随机字符串数组的排序
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 给定数组范围的选择排序问题
- 选择排序算法生成无序结果
- 使用C 中的一系列字符串的选择排序
- c++中对结构体数组使用排序选择