Search code examples
c#arrayssortingbubble-sort

c# 2D array bubblesort


I am trying to perform a bubble sort on a 2D array, sorting by the third index (the integer)

string[,] edges = new string[,] { {"A", "B", "2"},
                                          {"A", "C", "3"},
                                          {"A", "E", "10"},
                                          {"B", "C", "5"},
                                          {"B", "D", "10"},
                                          {"C", "D", "2"},
                                          {"D", "E", "5"},
                                          {"E", "B", "3"}
                                        }; 

I get an IndexOutOfRangeException on IF statenent of the sort code

        string[] temp = {};

        //sort edges and add them to sortedEdges - using bubblesort
        for (int i = 0; i < edges.Length - 1; i++){
            for (int j = 0; j < edges.Length - 1; j++){
                if (Int32.Parse(edges[i, 2]) > Int32.Parse(edges[i + 1, 2])){
                    //make a swap
                    //put array record i into temp holder
                    temp[0] = edges[i, 0];
                    temp[1] = edges[i, 1];
                    temp[2] = edges[i, 2];

                    //copy i + 1 into i
                    edges[i, 0] = edges[i + 1, 0];
                    edges[i, 1] = edges[i + 1, 1];
                    edges[i, 2] = edges[i + 1, 2];

                    //copy temp into i + 1
                    edges[i + 1, 0] = temp[0];
                    edges[i + 1, 1] = temp[1];
                    edges[i + 1, 2] = temp[2];

                }
            }
        }

My question is, how do I fix this so that the array "edges" is filled with the rows, ordered by the third column?

Thanks.


Solution

  • UPDATED v-3

    The problem was in Length for such defined table which in your case was 24 because it seems to count all the elements in both dimensions. Please try the following code:

    string[] temp = new string[3];
    
    for (int i = 0; i < edges.GetLength(0) - 1; i++){
        int j;
        j = 0;
        for (; j < edges.GetLength(0) - 1; j++){
    
            if (Int32.Parse(edges[j, 2]) > Int32.Parse(edges[j + 1, 2])){
                //make a swap
                //put array record j into temp holder
                temp[0] = edges[j, 0];
                temp[1] = edges[j, 1];
                temp[2] = edges[j, 2];
    
                //copy j + 1 into j
                edges[j, 0] = edges[j + 1, 0];
                edges[j, 1] = edges[j + 1, 1];
                edges[j, 2] = edges[j + 1, 2];
    
                //copy temp into j + 1
                edges[j + 1, 0] = temp[0];
                edges[j + 1, 1] = temp[1];
                edges[j + 1, 2] = temp[2];
    
            }
        }
    }
    

    You can find (updated) working example here: https://dotnetfiddle.net/FQs4OA