Reputation: 1150
I've written a bubblesort, however, when I print out the array, it's sorted, but it starts off with the highest number, and ends with the lowest number.
public int[] BubbleSort(int[] unsortedArray)
{
for(int i = 0; i < unsortedArray.Length; i++)
for(int j = 0; j < unsortedArray.Length; j++)
if(unsortedArray[i] < unsortedArray[j])
{
int temp = unsortedArray[i];
unsortedArray[i] = unsortedArray[j];
unsortedArray[j] = temp;
}
return unsortedArray;
}
Could anybody explain why the list is reversed.
EDIT: Sorry, pasted the wrong code.
When the line reads if(unsortedArray[i] < unsortedArray[j]) the list is orderded from lower to higher, however, this logically doesn't make sense. if i is lower than j, swap them.
Upvotes: 0
Views: 3779
Reputation: 1
int[] bd = new int[] { 25, 35, 104, 30, 89, 30, 42, 11, 8, 4, 55, 65, 98, 542, 2 };
for (int rnd = bd.Length; rnd > 0; rnd--)
{
for (int i = bd.Length - 1 ; i >= 0; i--)
{
if (i != 0)
{
if (bd[i - 1] < bd[i])
{
temp = bd[i];
bd[i] = bd[i - 1];
bd[i - 1] = temp;
}
}
}
}
for (int j = 0; j <= bd.Length - 1; j++)
{
Console.Write(bd[j] + Environment.NewLine);
}
Upvotes: 0
Reputation: 21477
Probably better as:
public int[] BubbleSort(int[] unsortedArray)
{
return unsortedArray.OrderBy(x=>x).ToArray();
}
A few issues with the original, i
and j
are iterating too much, it will still work, but it's doing unnecessary iterations that won't affect the outcome, also your conditional unsortedArray[i] < unsortedArray[j]
was backwards.
public int[] BubbleSort(int[] unsortedArray)
{
for(int i = 0; i < unsortedArray.Length-1; i++)
for(int j = i+1; j < unsortedArray.Length; j++)
if(unsortedArray[i] > unsortedArray[j])
{
int temp = unsortedArray[i];
unsortedArray[i] = unsortedArray[j];
unsortedArray[j] = temp;
}
return unsortedArray;
}
Optimized bubble sort:
public int[] BubbleSort(int[] unsortedArray)
{
var n=unsortedArray.Length;
while(n>0)
{
var newn=0;
for(var i=1;i<=n-1;i++)
{
if(unsortedArray[i-1]>unsortedArray[i])
{
var temp = unsortedArray[i];
unsortedArray[i] = unsortedArray[i-1];
unsortedArray[i-1] = temp;
newn=i;
}
}
n=newn;
}
}
Upvotes: 2
Reputation: 9224
it's this conditional
if(unsortedArray[i] < unsortedArray[j])
it should be
if(unsortedArray[j] < unsortedArray[i])
Edit: to answer your edit.
You want the element in unsortedArray[i]
to have the lowest value after the inner loop is run. Which means you only switch it out if you encounter a unsortedArray[j]
, that's less than the current value sitting in unsortedArray[i]
.
If unsortedArray[i]
is already the lower value, then leave it where it is.
Upvotes: 1
Reputation: 1497
Your compare in
if(unsortedArray[i] < unsortedArray[j])
should be
if(unsortedArray[i] > unsortedArray[j])
Upvotes: 0