C
C#2y ago
Darma

❔ Random Sort Assignment

I don't understand what it means by compare the pairs, as I tried using a for-loop to loop through the array and try to compare the current index with the next index after. I think I've been doing this in an ineffective way but can't figure out a better way to tackle this problem.
9 Replies
Darma
DarmaOP2y ago
public static bool checkIfSorted(int[] array)
{
bool sorted = false;

for (int i = 0; i < array.Length; i++)
{
if (array[i] < array[i+1])
{
sorted = true;
Console.WriteLine("Hooray it's sorted!");
}
else
{
sorted = false;
Console.WriteLine("Not sorted yet!");
}
}

return sorted;
}
public static bool checkIfSorted(int[] array)
{
bool sorted = false;

for (int i = 0; i < array.Length; i++)
{
if (array[i] < array[i+1])
{
sorted = true;
Console.WriteLine("Hooray it's sorted!");
}
else
{
sorted = false;
Console.WriteLine("Not sorted yet!");
}
}

return sorted;
}
I ran the code and realized that it's just going to spam the lines I've told the console to write the moment that 2 values happen to be sorted properly as opposed to the entire table being sorted
Angius
Angius2y ago
You should break out of the loop as soon as you find an unsorted pair Otherwise, even if an unsorted pair is found, sorted will change the value again as soon as a sorted pair occurs And vice versa And, yes, of course it will spam the lines You print them with every loop iteration
Kouhai
Kouhai2y ago
The code will also throw an IndexOutOfBound exception
Darma
DarmaOP2y ago
Yeah I ran it and saw that as well I'm dealing with a 1D array so I'm wondering how I compare 2 consecutive indexes at the same time
Angius
Angius2y ago
The way you currently do Just mind the indexes array.Length will already return a value 1 higher than the last index Then, when comparing, you additionally do i + 1 in one spot
Darma
DarmaOP2y ago
for (int i = 0; i < array.Length; i++)
{
if (array[i] < array[i])
{
sorted = true;
Console.WriteLine("Hooray it's sorted!");
}
else
{
sorted = false;
Console.WriteLine("Not sorted yet!");
break;
}
}
for (int i = 0; i < array.Length; i++)
{
if (array[i] < array[i])
{
sorted = true;
Console.WriteLine("Hooray it's sorted!");
}
else
{
sorted = false;
Console.WriteLine("Not sorted yet!");
break;
}
}
where would the i + 1 be placed
Angius
Angius2y ago
uh Where it used to be placed...? But you shouldn't be iterating up to array.Length More like array.Length - 1 Or even - 2
Darma
DarmaOP2y ago
Gotcha
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?