If you want to use your single array sorting algorithm (bubble sort) to sort the two dimensional array then you have to add the another for loop: An outer for loop which will take care of each row. Let's say m is number of row and n is number of column.

for(k=0; k< m; k++) {
   for (i = 0; i < n; i++) {
     for (j = i +1; j < n; ++j) {
       if (array2[k][i] > array2[k][j])  {
           int swap = array2[k][i];
           array2[k][i] = array2[k][j];
           array2[k][j] = swap;
       }
     }
   } 
}

But this is not an efficient approach to sort the array, it's time complexity will be O(mn^2)

Answer from Amit Sharma on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-program-to-sort-2d-array-across-rows
C Program To Sort 2D Array Across Rows - GeeksforGeeks
July 23, 2025 - In this approach, we use Bubble Sort. First Start iterating through each row of the given 2D array, and sort elements of each row using the Bubble sort sorting algorithm. Below is the implementation of the above approach: ... // C program to ...
Discussions

sorting - How to sort strings in an 2D array in C - Stack Overflow
So as a junior CE student our task is to write a C code that sort the strings in a 2D array according to their first characters position in the alphabet by only using the library and this is the result I get is below(I know the variables are not really bearable but I'm in a little ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
sorting of 2d arrays in C - Stack Overflow
i'm a beginner in c. and a little bit confused about 2-d arrays which was pretty easy in python. let's suppose i declare an array[100][2] and take their readings. then i want to sort the elements t... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Sort 2D array in C - Stack Overflow
The macro can only work on arrays ... of the array once it's decayed to a pointer; it will give the size of the pointer. 2014-11-27T10:32:44.503Z+00:00 ... The error is not in the code you posted. Build a minimal, compileable example that still exhibits the error, then I can help. It was odd, by the way, that you didn't get garbage in your output when you sorted four times ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Sorting a 2D array using insertion sort (C++)
Are you trying to sort the 2D array as if it were one long 1D array? More on reddit.com
๐ŸŒ r/programminghelp
3
1
June 17, 2022
๐ŸŒ
Quora
quora.com โ€บ How-can-I-sort-a-2D-array-of-size-3x3-in-ascending-order-in-C-language-Can-you-explain-it-with-the-simple-concept
How to sort a 2D array of size 3x3 in ascending order in C language? Can you explain it with the simple concept - Quora
Answer (1 of 2): Hey, thanks for asking. You can simply convert a 2D array to 1D, sort it and convert 1D array back to 2D. The code for the above explanation is as follows : [code]#include #include void main() { int arr[3][3],b[9]; int i,j,k=0,temp; clrscr();...
๐ŸŒ
Quora
quora.com โ€บ How-do-I-sort-a-2D-array-according-to-values-in-any-given-column-in-C-C++
How to sort a 2D array according to values in any given column in C/C++ - Quora
Answer: Recently I needed to do this with a plain int array, and came up against some problems. C++ does not like you messing around with arrays as objects very much. Particularly [code ]std::sort[/code] does not like reassigning rows in a 2D array. Arrays are not really first class objects like ...
๐ŸŒ
Quora
quora.com โ€บ How-do-I-sort-a-2D-struct-array-in-C
How to sort a 2D struct array in C - Quora
Answer: First, you have to define what it means to sort a 2-D array of anything. Let's ignore C and structs for a moment. Suppose I have this 3ร—3 array of integers: [code]{{ 3, 5, 7 }, { 9, 2, 6 }, { 4, 8, 1 }} [/code]What should the sorted output look like? Are youโ€ฆ * โ€ฆsorting the rows, co...
๐ŸŒ
Blogger
see-programming.blogspot.com โ€บ 2013 โ€บ 07 โ€บ c-program-to-sort-two-dimensional-array_27.html
Computer Programming And Technology For Dummies: C program to sort two dimensional array in descending order
July 27, 2013 - Correctly executed just made some changes in it to make it applicable to any array where number of rows and column can be different // Updated by Shrinivas #include #define ROW 10 #define COL 10 int main() { int mat[ROW][COL]; int i, j, k, l, n, m, tmp; /* get the order of the matrix from the user */ printf("Enter the rows of the matrix:"); scanf("%d", &n); printf("Enter the column of the matrix:"); scanf("%d", &m); /* get the matrix entries from the user */ printf("Enter your entries for the input mat:\n"); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { scanf("%d", &mat[i][j]); } } /* so
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ c-programming โ€บ 159880-sorting-2d-array-column.html
sorting a 2d array by column
October 24, 2013 - #include <stdio.h> #include <stdlib.h> #define ARRSIZE(arr) (sizeof(arr)/sizeof(*(arr))) int compare(const void *a, const void *b) { int x1 = *(const int*)a; int x2 = *(const int*)b; if (x1 > x2) return 1; if (x1 < x2) return -1; // x1 and x2 are equal; compare y's int y1 = *(((const int*)a)+1); int y2 = *(((const int*)b)+1); if (y1 > y2) return 1; if (y1 < y2) return -1; return 0; } int main(void) { int matrix[][2] = {{8,6}, {4,2}, {1,0}, {4,8}, {2,4}, {4,3}, {1,2}, {2,2}, {8,3}, {5,5}}; printf("Original: "); for (size_t i = 0; i < ARRSIZE(matrix); i++) printf("(%d,%d) ", matrix[i][0], matrix[i][1]); putchar('\n'); qsort(matrix, ARRSIZE(matrix), sizeof(*matrix), compare); printf("Sorted : "); for (size_t i = 0; i < ARRSIZE(matrix); i++) printf("(%d,%d) ", matrix[i][0], matrix[i][1]); putchar('\n'); return 0; }
Find elsewhere
Top answer
1 of 2
1

Limited to stdio.h

If you are limited to using what is provided in stdio.h, then you simply have to write similar string handling functionality to what you would require from string.h. For sorting, unless you want to use a partitioning sort like quicksort or mergesort, you would be limited to a nested loop sort -- which are simpler to write -- but much much slower. (but for a 1000 or so strings, it doesn't matter, 100,000 - then there will be a perceivable difference)

To compare strings, you can write a simple strcmp() like function that requires no additional header, e.g.

/** string compare without string.h */
int strcmp_nohdr (const char *a, const char *b)
{
    if (!a && !b) return 0;
    if ( a && !b) return 1;
    if (!a &&  b) return -1;

    for (; *a && *a == *b; a++, b++) {}

    return (*a > *b) - (*a < *b);
}

If you are not declaring an additional set of pointers to sort, then you will need to copy strings between the rows (1D arrays) in your 2D array. You can write a simple strcpy() like function that needs no header as:

/** string copy wihout string.h */
char *strcpy_nohdr (char *dest, const char *src)
{
    char *p = dest;
    
    do {
        *p++ = *src;
    } while (*src++);
    
    return dest;
}

Finally, the only other thing you need is a sort function. (you will not be able to write a quick qsort() replacement) The meager Bubblesort will do. You can write a function to sort your 2D array of strings as:

#define NCHR 50

/** bubble sort of strings in 'a' (highly inefficient) */
void bubblesort2D (char (*a)[NCHR], size_t n)
{
    size_t i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < (n-1); j++) {
            if (strcmp_nohdr(a[j], a[j + 1]) > 0) {
                char temp[NCHR];
                strcpy_nohdr (temp, a[j + 1]);
                strcpy_nohdr  (a[j + 1], a[j]);
                strcpy_nohdr  (a[j], temp);
            }
        }
    }
}

If you put those altogether in a short example (the same used before with qsort(), you would have:

#include <stdio.h>

#define NCHR 50

/** string compare without string.h */
int strcmp_nohdr (const char *a, const char *b)
{
    if (!a && !b) return 0;
    if ( a && !b) return 1;
    if (!a &&  b) return -1;

    for (; *a && *a == *b; a++, b++) {}

    return (*a > *b) - (*a < *b);
}

/** string copy wihout string.h */
char *strcpy_nohdr (char *dest, const char *src)
{
    char *p = dest;
    
    do {
        *p++ = *src;
    } while (*src++);
    
    return dest;
}

/** bubble sort of strings in 'a' (highly inefficient) */
void bubblesort2D (char (*a)[NCHR], size_t n)
{
    size_t i, j;
    for (i = 0; i < n; i++) {
        for (j = 0; j < (n-1); j++) {
            if (strcmp_nohdr(a[j], a[j + 1]) > 0) {
                char temp[NCHR];
                strcpy_nohdr (temp, a[j + 1]);
                strcpy_nohdr  (a[j + 1], a[j]);
                strcpy_nohdr  (a[j], temp);
            }
        }
    }
}

int main (void) {
    
    char strings[][NCHR] = { "zebra", "alligators", "frogs", "racoons", "opossums" };
    size_t n = sizeof strings / sizeof *strings;
    
    bubblesort2D (strings, n);
    
    for (size_t i = 0; i < n; i++)
        puts (strings[i]);
}

Example Use/Output

The results are the same as before:

$ ./bin/sort_2d_strings_stdio
alligators
frogs
opossums
racoons
zebra

Since I originally wrote the qsort() answer, I'll leave it below as the way you would want to handle sorting (whatever array you are sorting) in practice.

In Practice Use qsort()

C provides qsort() that will sort arrays of any object based on the compare function you write to tell qsort() how elements of the array are to be compares. With strings, you just want to return the result of strcmp(). Each argument to the compare function ia a Pointers to an element of your array. Since it is a void* pointer, you must cast the pointer back to the correct type.

Recall in C that a 2D array is simply an array of 1D arrays. In your case it is a array of 50-character arrays. A pointer to an array of 50-chars has the type char (*)[50], so your qsort() compare function can be written as follows:

int cmpstr50 (const void *a, const void *b)
{
    const char  *pa = *(char (*)[50])a,
                *pb = *(char (*)[50])b;
    
    return strcmp (pa, pb);
}

Where each of the parameters is a pointer to an array of char [50]. Nothing could be easier. Moreover the algorithm used by qsort() will be orders of magnitude faster than what you write with nested loops.

A complete example for your case would be:

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

int cmpstr50 (const void *a, const void *b)
{
    const char  *pa = *(char (*)[50])a,
                *pb = *(char (*)[50])b;
    
    return strcmp (pa, pb);
}

int main (void) {
    
    char strings[][50] = { "zebra", "alligators", "frogs", "racoons", "opossums" };
    size_t n = sizeof strings / sizeof *strings;
    
    qsort (strings, n, sizeof *strings, cmpstr50);
    
    for (size_t i = 0; i < n; i++)
        puts (strings[i]);
}

Where after writing your compare function, all it takes to sort the array of strings (or array of anything) is a single call to qsort():

    qsort (strings, n, sizeof *strings, cmpstr50);

Much simpler than trying to reinvent the wheel.

Example Use/Output

$ ./bin/qsort_2d_strings
alligators
frogs
opossums
racoons
zebra

Let me know if you have further questions.

2 of 2
0

This comparison is incorrect:

while((dict[j][1]<dict[k-1][1]) && (k>0))

First, if you want to compare the first character of each word, use [0] instead of [1]. This is because array indexes are zero-based in C. Second, put the k>0 comparison first, before you use k-1 as an index to the array. This will take advantage of "short circuiting" to make sure you're not using an invalid index to the array. Result:

while(k > 0 && dict[j][0] < dict[k-1][0])

Another issue is that you are not making sure your strings are null terminated when you copy them. I believe this is the reason your "SEALION" is coming out "SEALI". For example, this loop:

x=0;
while(dict[k][x]!= '\0')
{
    dict[k][x]=tmp[x];
    x=x+1;
}

You're checking for null on the destination instead of the source. Also, you stop copying at the null character, but you actually need to copy that too, or at least tack a null at the end:

x=0;
while(tmp[x]!= '\0')
{
    dict[k][x]=tmp[x];
    x=x+1;
}
dict[k][x] = '\0';

Take a close look at each of your string copy loops for such errors.

๐ŸŒ
OneCompiler
onecompiler.com โ€บ c โ€บ 3zed5e4f6
sorting 2D Array - C
Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index.
๐ŸŒ
Electro4u
electro4u.net โ€บ blog โ€บ write-a-program-to-short-2d-array-using-bubble-short-in-c-602
Sorting a 2D Array with Bubble Sort in C: Practical Example
For each row, compare adjacent elements and swap them if they are in the wrong order. Repeat steps 1 and 2 until the array is sorted. ... #include <stdio.h> void bubble_sort_2d(int array[][10], int rows, int columns) { for (int i = 0; i < rows; i++) { for (int j = 0; j < columns - 1; j++) { ...
๐ŸŒ
Reddit
reddit.com โ€บ r/programminghelp โ€บ sorting a 2d array using insertion sort (c++)
r/programminghelp on Reddit: Sorting a 2D array using insertion sort (C++)
June 17, 2022 -

So i am trying to sort an entire 2D array using insertion sort but i always encounter an error where the program only sort each row of the array. i've tried some algorithm that i made myself but it just make the program crash. can anyone tell me what's going on here? Below is my code

#include <iostream>
#include <conio.h>
using namespace std;

int main(){
	int temp, k, v, h, l = 0;
	int data[3][4], sorted[3][4];
	int a[9] = {1,4,6,3,9,8,5,7,2};

	for(int i = 0; i < 3; i++){
		for(int j = 0; j < 4; j++){
			if(l < 9){
				data[i][j]=a[l];
				l++;
			}
			else{
				data[i][j]=0;
			}
		}
	}
	
	for(int i = 0; i < 3; i++){
		for(int j = 0; j < 4; j++){
			cout<<data[i][j]<<"  ";
		}
		cout<<endl;
	}
	cout<<endl<<endl;
	//sorting
	for(int i = 0; i < 3; i++){
		for(int j = 0; j < 4; j++){
            temp = data[i][j];
            k = j-1;
            while(k >= 1 && temp <= data[i][k]){
            	data[i][k+1] = data[i][k];
	            k = k-1;
            }
            if(temp >= data[i][k])
                data[i][k+1] = temp;
            else{
                data[i][k+1] = data[i][k];
                data[i][k] = temp;
            }
        }
	}
	//sorting baru
	
	for(int i = 0; i < 3; i++){
		for(int j = 0; j < 4; j++){
			cout<<data[i][j]<<"  ";
		}
		cout<<endl;
	}
}

๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ general โ€บ 87088
Sorting 2D arrays - C++ Forum
... 2D Arrays to Array -> stort Array -> build 2D Arrays [1,2,3] [4,5,6] [7,8,9] -> [1,2,3,4,5,6,7,8,9] -> [9,8,7,6,5,4,3,2,1] -> [7,8,9] [4,5,6] [1,2,3] ... @monkey11: that's no help at all @topic: for the first sort you need 1 for loop, 1variable to save the maximum of each run, 1variable to swap elements of that array...
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ general โ€บ 282892
Sorting in 2d array - C++ Forum
March 28, 2022 - Most of the time, again depending on # of columns, the 2d sort is going to run a lot faster than 1-d (and it did above with standard sort too, the type of sort does not change this fact, just changes how much work is done either way). ... @jonnin So time complexity will be O(n^3) or O(n^2) because in 1d array bubble sort has two loops but for 2d array bubble sort has three loops
๐ŸŒ
Tutorial At Home
tutorialathome.in โ€บ string โ€บ 2d-string-array-sort-c-language
2D String Array Sort - String - C Language - Tutorial At Home
May 31, 2019 - #include<string.h> #include<stdio.h> #include<conio.h> int main() { int i,j; char names[5][30],temp[30]; printf("Enter 5 Names\n"); for(i=0;i<5;i++) { gets(names[i]); } for(i=0;i<5;i++) { for(j=i+1;j<5;j++) { if(strcmp(names[i],names[j])>0) { strcpy(temp,names[i]); strcpy(names[i],names[j]); strcpy(names[j],temp); } } } printf("\n\n OUTPUTS \n\n"); for(i=0;i<5;i++) { puts(names[i]); } } ... I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata.
Top answer
1 of 8
16

I'm offering this up only because it was one of the few things std::qsort does well that std::sort simply does not, namely sort multi-column fixed arrays: The comparator is a string of ternary statements, but should be clear enough if you stare at it long enough:

#include <iostream>
#include <random>
#include <algorithm>

int main()
{
    int ar[10][2];

    // populate with random data
    std::random_device rd;
    std::default_random_engine rng(rd());
    std::uniform_int_distribution<> dist(1,20);
    std::for_each(std::begin(ar), std::end(ar),
        &[2]){ ar[0] = dist(rng); ar[1] = dist(rng); });

    std::cout << "Before Sort..." << '\n';
    std::for_each(std::begin(ar), std::end(ar),
        [2]) { std::cout << ar[0] << ',' << ar[1] << '\n';});

    std::qsort(ar, 10, sizeof(*ar),
        ->int
        {
            int const *lhs = static_cast<int const*>(arg1);
            int const *rhs = static_cast<int const*>(arg2);
            return (lhs[0] < rhs[0]) ? -1
                :  ((rhs[0] < lhs[0]) ? 1
                :  (lhs[1] < rhs[1] ? -1
                :  ((rhs[1] < lhs[1] ? 1 : 0))));
        });

    std::cout << "After Sort..." << '\n';
    std::for_each(std::begin(ar), std::end(ar),
        [2]) { std::cout << ar[0] << ',' << ar[1] << '\n';});

    return 0;
}

Sample Run (yours will vary, obviously)

Before Sort...
2,11
18,4
20,20
14,6
8,10
17,8
14,14
3,10
20,14
19,19
After Sort...
2,11
3,10
8,10
14,6
14,14
17,8
18,4
19,19
20,14
20,20

Notes: this specifically uses strict-value comparison rather than subtraction short-cuts in the comparator so as to avoid potential underflow issues. If that is not a problem in your restricted data-space, you could easily make that comparator significantly simpler.

2 of 8
12

The built-in arrays of C and C++ are very inflexible, among other things they cannot be assigned.

Your best option would be the 'array' class from the C++ standard library, at least for the inner dimension:

array<int, 2> a[5] = { { 20, 11 },
{ 10, 20 },
{ 39, 14 },
{ 29, 15 },
{ 22, 23 } };

sort( a, a + 5 );

Edit: Some more explanations.

Here we use the property of std::array that '<' by default compares them lexicographically, i.e. starts with the first element. In order to sort things differently we have to come up with an comparator object, so if you want to use the second column as sort key you have to do this:

auto comp = 
      { return u[1] < v[1]; };
sort( a, a + 5, comp );

And as mentioned in the first comment, sort(a, a+5 ... is just an ugly short form for the cleaner sort(std::begin(a), std::end(a) ...

๐ŸŒ
Google Sites
sites.google.com โ€บ view โ€บ learnprog โ€บ notes โ€บ list-of-c-programs โ€บ sort-2d-array-column-wise
Learn Programming - sort-2d-array-column-wise
To sort the columns of a 2-d array we can apply bubble sort column wise. While comparing the items items are compared row-wise. Once all the items of a column placed in ascending order then next column is considered.