繁体   English   中英

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

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

因此,我尝试执行此选择排序方法,该方法读取您的数组并将其显示范围从最小到您知道

“这些是未排序的数组29315

这些是排序后的数组95321“

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

PS:我试图描绘代码以使动态数组然后排序。 我该怎么做? 正如您在下面看到的那样,我让用户输入自己的数组,但限制为n AKA1000。请问如何解决该问题。 谢谢

#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(即5次)运行。 因此,您只能输入五个数字

您可以如下修改此循环:

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

PS:我试图描绘代码以使动态数组然后排序。 我该怎么做? 如下所示,我让用户输入他们自己的数组,但限制为n AKA1000。请问如何解决该问题。 谢谢

您的要求不清楚。 请重新陈述您的问题。 如评论中所述,我认为不需要n 您可以要求用户输入数组所需的元素数,即k ,然后可以为如此多的整数动态分配空间,如下所示:

int *a = new int[k];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM