簡體   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