我想按字母顺序对数组进行排序,如下所示:
各种方法都试过了,还是不行。它崩溃了,还不知道为什么。您有一些技巧可以帮助您解决这个问题吗?
由于我不是专家,所以代码旨在简单(阅读/理解)和完成工作。
谢谢,问候
/* note: datalist[...] is basically the ouput from a sort of ls (dir
read) that it unsorted. So that: datalist[0] is ".." datalist[1] is
"file2.c" datalist[2] is "file34.c" and so on.*/
char datalist[500][2024] ;
void sortData(int aoptiondt) { ///////////////////////////LOCAL
DECLARATIONS///////// int MAX = 500 ; int current; int walker;
int smallestIndex; char* temp;
///////////////////////////DEFINITIONS//////////////////
for (current = 0; current < MAX - 1; current++)
{
smallestIndex = current;
for (walker = current; walker < MAX ; walker ++)
{
if (strcmp(datalist[walker], datalist[smallestIndex]) < 0)
smallestIndex = walker;
} //for walker
//Swap to position smallest at what is the current position
strncpy( temp , datalist[current] , PATH_MAX);
strncpy( datalist[current] , datalist[smallestIndex] , PATH_MAX);
strncpy( datalist[smallestIndex] , temp, PATH_MAX);
} //for current }
return; }
//blabla
int main() {
}
最佳答案
一如既往 - qsort
是您最好的 friend :
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 6
#define STRING_SIZE 4
#define STRINGS "eed", "abd", "cde", "abc", "acd", "ade"
char strUnsorted[][STRING_SIZE] = {STRINGS};
char strSorted[][STRING_SIZE] = {STRINGS};
int compare (const void * a, const void * b) {
return strcmp(a, b);
}
int main () {
qsort(strSorted, LENGTH, STRING_SIZE, compare);
printf("Unsorted | Sorted\n");
printf("-----------------\n");
int i;
for (i=0; i < LENGTH; i++)
printf (" %s | %s\n", strUnsorted[i] ,strSorted[i]);
return 0;
}
关于c - 在 C 编程语言中按字母顺序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14974291/