如何使用冒泡排序和对带字符串的二维数组进行排序

How to use the bubble sort and sorting a 2d array with strings

我想要一个主程序,它使用 scanf(最多 100 个字符)读取 10 个名称,将它们保存到二维数组 (char[10][100]),然后调用具有该算法的函数冒泡排序并对二维数组进行排序。最后我希望主程序打印排序后的二维数组。

函数原型为:

void bubble_sort(str[][100]);

有人能告诉我代码吗?

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

#define SIZE 10

void bubble_sort(char str[SIZE][100]);

int main (void) {
    char names[SIZE][100];
    int i, j;
    for (i = 0; i < SIZE; i++) {
        printf("Enter names: ");
        scanf("%s", names[i]);
    }

    bubble_sort(names);

    for (int i = 0; i < SIZE; i++)
        printf ("%s\n", names[i]);
}

void bubble_sort(char str[SIZE][100]) {
    int i, j, reorder = 0;
    char temp;

    for (i = 1; i < SIZE; i++) {
        for (j = SIZE - 1; j >= i; j--) {
            if (strcmp(str[j], str[j + 1]) > 0) {
                strcpy(temp, str[j + 1]);
                strcpy(str[j + 1], str[j]);
                strcpy(str[j], temp);
                reorder = 1;
            }
        }
        if (reorder == 0)
            return;
    }
}

我希望输入 10 个名字,然后以字母升序的方式将这 10 个名字作为输出。

这是我的回答,希望对你有用。

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

#define SIZE 10

void bubble_sort(char str[SIZE][100]);

int main (void) 
{
    char names[SIZE][100];
    printf("The max length of name is 99\n");
    int i;
    for(i=0;i<SIZE;i++){
        printf("Enter names:");
        scanf("%99s",names[i]);
    }

    bubble_sort (names);

    for (int i = 0; i < SIZE; i++)
        printf ("%s\n", names[i]);
    return 0;
}

void bubble_sort (char str[SIZE][100])
{
    int i, j;
    char temp[100] = {0};

    for (i = 0; i < 10 - 1; i++) {
        for (j = 0; j < 10 - 1 - i; j++) {
             if (strcmp(str[j], str[j + 1]) > 0) {
                strcpy(temp, str[j]);
                strcpy(str[j], str[j + 1]);
                strcpy(str[j + 1], temp);
            }
        }
    }

}

以上程序输出为:

Enter names:ca
Enter names:sd
Enter names:fgg
Enter names:cb
Enter names:dssd
Enter names:hgf
Enter names:jydt
Enter names:jdjy
Enter names:dgr  
Enter names:htr
ca
cb
dgr
dssd
fgg
hgf
htr
jdjy
jydt
sd