2d array help

I have found many topics to learn sorting,searching of 1 d array in many of books but still could not find any topic about sorting and searching in 2D ARRAY.I am a university student and i need urgent help please help me from which book or which website i could easily and throughly learn SORTING AND SEARCHING IN 2D ARRAY?
2D arrays are exactly like 1D arrays. Just apply the same methodology but include an additional for loop and do some additional logic to compare the current 1D array with the next 1D array.

As an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const int n = 10, m = 10;
float a[n][m];

for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        cin >> a[i][j];

bool sorted = true;
while (sorted)
{
    for (int i = 0; i < n; i++)
    {
        // normal sorting for array a[i][...];
        for (int j = 0; j < (m-1); j++)
        {
            if (a[i][j] > a[i][j+1])
            {
                float temp = a[i][j];
                a[i][j] = a[i][j+1];
                a[i][j+1] = temp;
                sorted = false;
            }
        }

        // Lets compare the last value in this array to the first value in the next array
        if (i < n-1) //don't do this on the last array.
        {
            if (a[i][m-1] > a[i+1][0])
            {
                float temp = a[i][m-1];
                a[i][m-1] = a[i+1][0];
                a[i+1][0] = temp;
                sorted = false;
            }
        }
    }
}

for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        cout << a[i][j] << ','; //They are all in order. 


Now this is not the most efficient way to do this. It will be very slow if the array size is large, but you can see what we've done.
Last edited on
shouldn't there be a { after the "for" loop? Or is this some other style I'm still not aware of?

*Edit: Also a closing one.
Last edited on
If there is only one statement after a loop or if statement, you don't need the brackets.

In this case, each for loop only has one statement, so it's perfectly fine. (:
Thanks for clarifying this to me, I just learnt an new thing :D
ahaha nice pun :P

Wrong place! I thought this was a different post where I told someone about the new keyword... ahaha!

Anyway, you're welcome!
Last edited on
Topic archived. No new replies allowed.