Scala:Bubble Sort

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items.

 

object Bubblesort extends App{

var arr=Array(5,4,2,1,5,8)
var swap = 0
def bubsort(x:Array[Int]):Array[Int]=
{
for(i<-0 to x.length-2)
{
for(j<-0 to x.length-2)
{
if (arr(j)>arr(j+1))
{
swap=arr(j+1)
arr(j+1)=arr(j)
arr(j)=swap
}

}
}
arr
}

var a = bubsort(arr)
for(i<-0 to a.length-1)
{
print(a(i))
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s