Search code examples
c#arrayssortingbubble-sort

Reverse order of bubble sort of null elements


I'm trying to reverse my bubble sort so all null elements are pushed to the end of array instead of the beginning as they're getting sorted now. Any advice on how this can be achieved?

            for (int outerLoop = 0; outerLoop < students.Length-1; outerLoop++)
            {
                for (int innerLoop = 0; innerLoop < students.Length-1; innerLoop++)
                {
                    if (students[outerLoop+1] == null)
                    {
                        var tempObject = students[outerLoop+1];
                        students[outerLoop+1] = students[innerLoop];  
                        students[innerLoop] = tempObject;
                    }
                }
            }

Solution

  • Corrected code:

            for (int outerLoop = 0; outerLoop < students.Length-1; outerLoop++)
            {
                for (int innerLoop = 0; innerLoop < students.Length-1; innerLoop++)
                {
                    if (students[innerLoop] == null)
                    {
                        var tempObject = students[innerLoop+1];
                        students[innerLoop+1] = students[innerLoop];  
                        students[innerLoop] = tempObject;
                    }
                }
            }
    

    This will not sort your array but only drop the nulls at the bottom.

    In fact you can do away with the temp variable:

            for (int outerLoop = 0; outerLoop < students.Length-1; outerLoop++)
            {
                for (int innerLoop = 0; innerLoop < students.Length-1; innerLoop++)
                {
                    if (students[innerLoop] == null)
                    {
                        students[innerLoop] = students[innerLoop+1];  
                        students[innerLoop+1] = null;
                    }
                }
            }
    

    Note: C# 7 introduced tuples which enables swapping two variables without a temporary one:

    int a = 10;
    int b = 2;
    (a, b) = (b, a);
    

    This assigns b to a and a to b.