c# - Bubblesort printing out in reverse order -
i've written bubblesort, however, when print out array, it's sorted, starts off highest number, , ends lowest number.
public int[] bubblesort(int[] unsortedarray) { for(int = 0; < 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 explain why list reversed.
edit: sorry, pasted wrong code.
when line reads if(unsortedarray[i] < unsortedarray[j]) list orderded lower higher, however, logically doesn't make sense. if lower j, swap them.
probably better as:
public int[] bubblesort(int[] unsortedarray) { return unsortedarray.orderby(x=>x).toarray(); }
a few issues original, i
, j
iterating much, still work, it's doing unnecessary iterations won't affect outcome, conditional unsortedarray[i] < unsortedarray[j]
backwards.
public int[] bubblesort(int[] unsortedarray) { for(int = 0; < 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; } }
Comments
Post a Comment