Reputation: 313
I am aware that there is a sort function available in C# to sort arrays into the correct order, but for reasons, I need to do it with my own code.
I have come up with this, and some of the numbers move, but it never fully sorts. Has anyone any idea why?
static void Main(string[] args)
{
int[] arraySort = { 2, 5, 7, 3, 6, 3 };
int save;
bool sorted = false;
while(sorted == false) {
for (int i = 0; i < (arraySort.Length - 1); i++)
{
sorted = true;
if (arraySort[i] > arraySort[i + 1])
{
save = arraySort[i];
arraySort[i] = arraySort[i + 1];
arraySort[i + 1] = save;
sorted = false;
}
}
}
for (int i = 0; i < arraySort.Length; i++)
{
Console.WriteLine(arraySort[i]);
}
}
My output ends up being:
2 3 5 3 6 7
Upvotes: 1
Views: 95
Reputation: 587
You set sorted=true every item you iterate, You need to do sorted=true outside of the for loop, between the while and the for.
while (sorted == false) {
sorted = true;// here seems like the right place!
for (int i = 0; i < (arraySort.Length - 1); i++)
{
if (arraySort[i] > arraySort[i + 1])
{
save = arraySort[i];
arraySort[i] = arraySort[i + 1];
arraySort[i + 1] = save;
sorted = false;
}
}
}
Upvotes: 2
Reputation: 9965
You set sorted = true
inside the for loop.
So it stops as soon as the penultimate entry is less than the final entry. All other checks are ignored when validating the outer loop
Upvotes: 2