algorithm - Bidirectional Bubble sort c# -
i have homework assignment of coding bidirectional bubble sort. can please see if logic correct respect it. don't want code want figure out myself. want logic check of how understand it.
as understand bidirectional bubble sort implement 2 loops 1 starting @ position 1 in list , performing normal bubble sort. first loop reaches end second 1 implemented working in reverse. don't understand terminating conditions each loop be.
would loop conditions follows?
loop 1 - for(i = 0; < count -i; i++)
loop 2 - for(j = count - i; j > i; j--)
in each loop swap conditions specified.
thanks
the "classic" bubble sort goes through entire array on each iteration, loops should be
for(i = 0; < count - 1; i++)
and
for(j = count - 1; j > 0; j--)
both loops skip 1 index: first loop skips last index, while second loop skips initial one. code safely compare data[i]
data[i+1]
, , data[j]
data[j-1]
.
edit "optimized" bubble sort skips initial k
elements on k
-th iteration. since bubble sort bidirectional, able skip initial k
, tail k
elements, this:
int k = 0; { // outer loop ... for(int = k; < count - k - 1; i++) ... for(int j = count - k - 1; j > k ; j--) ... k++; } while (<there swaps>);
Comments
Post a Comment