簡體   English   中英

隨機字符串數組的選擇排序

[英]Selection Sort of a Array of random strings

我正在嘗試創建一個選擇排序算法,該算法接受一組隨機字符串並對其進行排序。 我已經在網上查看並在我的書中嘗試使用 model 我的代碼,這就是我想出的。 我不確定我哪里出錯了,任何幫助將不勝感激。

Here is how you load the array with the random strings:
string Sorter::randomString() {
    string s = "";
    for (int i = 0; i < MAX_CHARS; i++) {
        char randomChar = char(rand() % 26 + 97);
    s += randomChar;
    }
    return s;
}

void Sorter::load() {
    for (int i = 0; i < MAX_STRINGS; i++)
        workspace[i] = randomString();

Here is my selection sort: 

void Sorter::selectionSort() {
    for (int pass = 0; pass < MAX_STRINGS - 1; pass++) {
        string smallest = workspace[pass];
    for (int pos = pass + 1; pos < MAX_STRINGS - pass - 1; pos++) {
            if (workspace[pos] > smallest) {
                smallest = workspace[pos];
            }
            swap(workspace[pos], workspace[pass]);
        }
    }
}

我希望對數組工作區進行排序,但事實並非如此:(

您的邏輯存在一些缺陷,因為您沒有正確設置列表中的最小元素。 您應該為此使用最小索引。

void selectionSort() {
    //Initialise minimum index
    int min_id = 0;
    //Loop through unsorted subarray 
    for (int pass = 0; pass < MAX_STRINGS - 1; pass++) {
        //Find the minimum element in rest of array
        min_id = pass;
        for (int pos = pass + 1; pos < MAX_STRINGS; pos++) {
            if (workspace[pos] < workspace[min_id]) {
                min_id = pos;
            }
        }
        //Swap the minimum element with current element in array
        swap(workspace[min_id], workspace[pass]);
    }
}

您無法正確找到未排序數組中的最小元素。 這是我的代碼:

void selectionSort(char arr[][MAX_STRINGS], int n)
{
    int i, j, min_idx;

    // One by one move boundary of unsorted subarray  
    char minStr[MAX_STRINGS];
    for (i = 0; i < n - 1; i++)
    {
        // Find the minimum element in unsorted array  
        int min_idx = i;
        strcpy_s(minStr, arr[i]);
        for (j = i + 1; j < n; j++)
        {
            // If min is greater than arr[j]  
            if (strcmp(minStr, arr[j]) > 0)
            {
                // Make arr[j] as minStr and update min_idx  
                strcpy_s(minStr, arr[j]);
                min_idx = j;
            }
        }

        // Swap the found minimum element with the first element  
        if (min_idx != i)
        {
            char temp[MAX_STRINGS];
            strcpy_s(temp, arr[i]); //swap item[pos] and item[i]  
            strcpy_s(arr[i], arr[min_idx]);
            strcpy_s(arr[min_idx], temp);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM