Michi
Michi

Reputation: 5297

bubble sort on Multi-dimensional Arrays

Today i tried to sort a Multi-dimensional Arrays and i just can't figure out, why it doesn't work.

The algorithm does the swap of first letter, but doesn't swap the whole string. Here is a working DEMO which shows that the algorithm prints alphabetically Initials of every string found.

The same algorithm used to swap the whole string not just the first letter, doesn't work:

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

int main(void){
    char arr[][10] = {"Michael" , "Tanja" ,"Adda", "Jenny", "Kimberly", "Walter" , "Donna"};
    size_t length = sizeof arr / sizeof *(arr + 0);
    unsigned int i,j, k=0;
    char *tmp;


    for (i = 0 ; i < length-1; i++){
        for (k = 0 ; k < length-i-1; k++){
            if (arr[k][0] > arr[k+1][0]){
                tmp = arr[k];
                strcpy(arr[k], arr[k+1]);
                strcpy(arr[k+1], tmp);
            }
        }
    }

    printf("Sorted Array:\n");
    for ( j = 0 ; j < length ; j++ ){
        printf("%s  ", arr[j]);
    }
    printf("\n\n");

    return 0;
}

Output which i get is:

Adda  Adda  Adda  Donna  Donna  Donna  Donna

and it should be:

Adda Donna Jenny Kimberly Michael Tanja Walter

Upvotes: 1

Views: 90

Answers (2)

ameyCU
ameyCU

Reputation: 16607

 tmp = arr[k];

Due to tmp pointing to arr[k] ,after copying arr[k+1] in arr[k] and copying tmp in latter , you get same value , as arr[k] is itself modified (tmp points to this modified value).

You can do this instead -

char tmp[20];
strcpy(tmp,arr[k]);

Upvotes: 3

P.P
P.P

Reputation: 121387

tmp is just a pointer. So during the assignment tmp = arr[k]; and subsequent strcpy(), it's lost due to arr[k] being overwritten with arr[k+1]. But you need to copy the string during swap. So use a buffer:

char tmp[256];

and

  strcpy(tmp , arr[k]);
  strcpy(arr[k], arr[k+1]);
  strcpy(arr[k+1], tmp);

Upvotes: 4

Related Questions