2017-11-03 100 views
1

我必須在C中編寫一個代碼,使用select排序算法將字符串按其長度排序。但排序不起作用,我不知道爲什麼:))按c選擇排序字符串的長度c

char * cityofMiddleEarth[CITIES] = { "Havens of Sirion", "Esgaroth", 
"Tirion", "Rivendell", "Romenna", "Hobbiton", "Carn Dum", 
            "Ephel Brandir", "Eldalonde", 
"Avallone", "Hyarastorni", "Linhir", "Minas Morgul", "Valmar", 
            "Waymeet", "Pelargir", "Obel Halad", 
"Bree", "Havens of the Falas", "Goblin Town", "Almaida" }; 

    int len, min, i, j; 
    len = sizeof(cityofMiddleEarth)/sizeof(cityofMiddleEarth[0]); 

    for (i = 0; i<len - 1; i++) 
    { 
     min = i; 
     for (j = i; j<len; j++) 
     { 
      if (cityofMiddleEarth[j]<cityofMiddleEarth[min]) 
      { 
       min = j; 
      } 
     } 

     char *temp = cityofMiddleEarth[i]; 
     cityofMiddleEarth[i] = cityofMiddleEarth[min]; 
     cityofMiddleEarth[min] = temp; 
    } 

回答

1

您正在比較指針,而不是字符串長度。要通過字符串長度排序,更改:

cityofMiddleEarth[j]<cityofMiddleEarth[min] 

到:

strlen(cityofMiddleEarth[j]) < strlen(cityofMiddleEarth[min]) 
+0

哦謝謝! <3 – arsy