簡體   English   中英

在C ++中以升序對數組集進行排序

[英]Sort set of array in ascending order in C++

我正在嘗試編寫代碼以對我的數組進行升序排序,因此發生的事情就是我所擁有的。

char myListArray[10][40];
myListArray = "Yeah?",
              "Tomorrow",
              "Again",
              "I will see you";

因此,發生的事情是應該按ASCII值對它進行排序。

Again
I will see you
Tomorrow
Yeah?

我已經創建了這樣的東西...

char temp[40];
temp[0] = '\0';           
int i, j, pos = 10, flag = 1;

for(i = 1; (i <= pos) && flag; i++)
{
    flag = 0;
    for (j=0; j < (pos -1); j++)
    {
        if (phrase[i][j+1] > phrase[i][j])     
        {
            strcpy(temp, phrase[i]);
            strcpy(phrase[i], phrase[i+1]);
            strcpy(phrase[i+1], temp);
            flag = 1;
        }
    }
}

現在,我不知道我的邏輯有問題,我想知道是否有一種可以簡單排序的函數? 還是bubble sort最簡單?

更新:

我將接受以下答案之一,但是我找到了如何以最簡單的方式對數組進行排序的解決方案。

while(pos < 9){

  if(phrase[pos][i] > phrase[pos+1][i]){


   strcpy(temp, phrase[pos]);
   strcpy(phrase[pos], phrase[pos+1]);
   strcpy(phrase[pos+1], temp);
   flag = 1;

 if(flag = 1){

    pos = 0;

  }


  }

pos++;

}

使用std::arraystd::stringstd::sort ...

std::array<std::string, 4> arr = { "Yeah?", "Tomorrow", "Again", "I will see you" };
std::sort(arr.begin(), arr.end());

如果您無權訪問std::array則也可以輕松地使用C數組或std::vectors

我想知道是否有一種功能可以輕松排序?

  • 嘗試使用C ++構造,例如stringvectorsort 這樣您的工作就會變得容易得多。
  • 但是,如果要使用C,則可以查找qsort 但是,您將需要提供自定義比較器功能。

冒泡排序最簡單?

排序算法的選擇取決於多種因素,例如最壞情況下的性能,元素數等。請考慮需要排序的元素數。 想想什么樣的表現是可以接受的。 IMO,實施冒泡排序與插入排序或Shell排序一樣容易。 合並排序/快速排序/基數排序OTOH,可能要稍微多一些。

如果您希望它像看起來那樣使用純C,那么您會錯過strcmpqsort 請注意,您的代碼與C ++ 無關 ,它是經典的C代碼,問題被誤解了。 如果要用C ++完成,請參閱其他實際使用C ++容器的答案。 如果您實際上並沒有使用C ++,那您就不用使用C ++了,而不僅僅是C!

以下是一個獨立的工作示例。 請注意,對於您的2D數組和指向字符串的指針數組都有一個示例。 您的2D數組聲明有多余的1st數組大小。 沒必要,編譯器知道那里有多少個字符串。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sort1(void)
{
    // 2D array
    char strings[][40] = {
        "Yeah?",
        "Tomorrow",
        "Again",
        "I will see you"
    };
    const int el_size = sizeof(strings[0]);
    const int el_count = sizeof(strings)/el_size;
    int i;
    printf("\n%s\n", __FUNCTION__);
    qsort(strings, el_count, el_size, strcmp);
    for (i = 0; i < el_count; ++i) {
        printf("%s\n", strings[i]);
    }
}

int strcmp_ptr(const char ** a, const char ** b)
{
    return strcmp(*a, *b);
}

void sort2(void)
{
    // Array of pointers to string constants
    const char * strings[] = {
        "Yeah?",
        "Tomorrow",
        "Again",
        "I will see you"
    };
    const int el_size = sizeof(strings[0]);
    const int el_count = sizeof(strings)/el_size;
    int i;
    printf("\n%s\n", __FUNCTION__);
    qsort(strings, el_count, el_size, strcmp_ptr);
    for (i = 0; i < el_count; ++i) {
        printf("%s\n", strings[i]);
    }
}

int main(void)
{
    sort1();
    sort2();
    return 0;
}

暫無
暫無

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

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