简体   繁体   中英

How to correctly implement an insertion sort algorithm in a 2D array?

I need to sort the columns of my 2D array based on the first row of the array. This is my 2d array before sorting:

cargo

AFADA
DAFGF
DXAFA
DDFFX
GFXF 

and this is the image of my 2D array:

acrgo

FAADA
ADFGF
XDAFA
DDFFX
FGXF

The correct output looks like this

acgor

FADAA
ADGFF
XDFAA
DDFXF
FGF X

. This is the code of my function to sort the array using insertion sort algorithm

void sort(char** newTable, int row, int col) {
    for (int top = 1; top < col; col++) {
        char item = newTable[0][top];
        int i = top;
        while (i > 0 && item < newTable[0][i - 1]) {
            for (int j = 0; j < row + 1; j++) {
                char temp = newTable[j][i];
                newTable[j][i] = newTable[j][i - 1];
                newTable[j][i - 1] = temp;
            }
            i--;
         }
         newTable[0][i] = item;
     }
 }

I called the function like this

    sort(newTable, row, strlen(key));

here, key is the string 'cargo'

The definition of newTable:

char** newTable = (char**)calloc(row + 1, sizeof(char*));
    for (int i = 0; i < row + 1; i++) {
        newTable[i] = (char*)calloc(strlen(key), sizeof(char));
    }

newTable is indeed an array of pointers and not a 2D array, so using char **newTable makes sense.

The major error is close to a typo: in the first for loop of sort , you increment col when you want to increment top . And the last line newTable[0][i] = item; is useless.

This should work (even if the loop for (int j = 0; j < row + 1; j++) suggests that row is not the number of rows in newTable but only the number of *additional rows):

void sort(char** newTable, int row, int col) {
    for (int top = 1; top < col; top++) {
        char item = newTable[0][top];
        int i = top;
        while (i > 0 && item < newTable[0][i - 1]) {
            for (int j = 0; j < row + 1; j++) {
                char temp = newTable[j][i];
                newTable[j][i] = newTable[j][i - 1];
                newTable[j][i - 1] = temp;
            }
            i--;
         }
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM