Search code examples
carraysstring2dbubble-sort

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


I want to have a main program that reads 10 names using scanf (maximum 100 characters), saves them to a 2D array (char[10][100]) and then calls a function that has the algorithm of the bubblesort and sorts the 2D array. And finally I want the main program to print the sorted 2D array.

The prototype of the function is:

void bubble_sort(str[][100]);

Can anybody show me the code?

#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;
    }
}

I expect to type 10 names and then get as an output these 10 names in an ascending alphabetical way.


Solution

  • This is my answer, hope it is useful for you.

    #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);
                }
            }
        }
    
    }
    

    The above program output is:

    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