Reputation: 487
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;
}
}
}
Upvotes: 0
Views: 255
Reputation: 186813
There's a faster, easier and stable approach with O(n)
time complexity:
int at = 0;
for (int i = 0; i < students.Length; ++i)
if (students[i] != null)
students[at++] = students[i];
for (int i = at; i < students.Length; ++i)
students[i] = null;
However, if you insist on bubble sort: we can implement it in a bit different way
for (bool wrongOrder = true; wrongOrder;) {
wrongOrder = false;
for (int i = 1; i < students.Length; i++) {
if (students[i - 1] == null && students[i] != null) {
// At least 2 items has wrong order, swap them
var temp = students[i - 1];
students[i - 1] = students[i];
students[i] = temp;
wrongOrder = true;
}
}
}
Upvotes: 1
Reputation: 11209
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
.
Upvotes: 1
Reputation: 34421
Try following. You have to test for outer being null and inner not being null :
for (int outerLoop = 0; outerLoop < students.Length - 1; outerLoop++)
{
for (int innerLoop = outerLoop + 1; innerLoop < students.Length; innerLoop++)
{
if ((students[outerLoop] == null) && (students[innerLoop] != null))
{
var tempObject = students[outerLoop];
students[outerLoop] = students[innerLoop];
students[innerLoop] = tempObject;
}
}
}
Upvotes: 1