Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Odd-Even Sort Visualized

DZone's Guide to

Odd-Even Sort Visualized

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

The Odd/Even sort is a sorting algorithm which uses the concept of the  Bubble Sort to move elements around. Unlike Bubble sort, the Odd/Even sort compares disjointed pairs by using alternating odd and even index values splitting the sorting in different phases. We have that in the odd phase all the element with an odd index i are compared with the adjacent even index i+1 and in the even phase all the element with an even index i are compared with the adjacent odd index i+1. These two phases are repeated until no exchanges are required. This is a Python snippet that make us able to visualize the behavior of the algorithm:
def oddeven_anim(a):
 imgidx =0
 x = range(len(a))
 sort =False;whilenot sort:
  sort =True;for i in range(1,len(a)-1,2):# odd phaseif a[i]> a[i+1]:
    a[i+1], a[i]= a[i], a[i+1]
    sort =False;for i in range(0,len(a)-1,2):# even phaseif a[i]> a[i+1]:
    a[i+1], a[i]= a[i], a[i+1]
    sort =False;
  pylab.plot(x,a,'k.',markersize=6)
  pylab.savefig("oddevensort/img"+'%04d'% imgidx +".png")
  pylab.clf()
  imgidx =  imgidx +1# run the algorithm
a = range(300)
shuffle(a)
oddeven_anim(a)
As in the other examples of sorting visualization in this blog, we have an image for each step of the algorithm. The following video have been produced joining all the images ( here is explained how):

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}