Skip to content

Commit 4442a1a

Browse files
authored
Merge pull request tulika-99#58 from monil/bubblesort-scala
Bubble Sort implementation in Scala
2 parents 1fe79c4 + d8fdd31 commit 4442a1a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Bubble Sort
2+
3+
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
4+
Example:
5+
First Pass:
6+
( 5 1 4 2 8 ) �> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
7+
( 1 5 4 2 8 ) �> ( 1 4 5 2 8 ), Swap since 5 > 4
8+
( 1 4 5 2 8 ) �> ( 1 4 2 5 8 ), Swap since 5 > 2
9+
( 1 4 2 5 8 ) �> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
10+
Second Pass:
11+
( 1 4 2 5 8 ) �> ( 1 4 2 5 8 )
12+
( 1 4 2 5 8 ) �> ( 1 2 4 5 8 ), Swap since 4 > 2
13+
( 1 2 4 5 8 ) �> ( 1 2 4 5 8 )
14+
( 1 2 4 5 8 ) �> ( 1 2 4 5 8 )
15+
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
16+
Third Pass:
17+
( 1 2 4 5 8 ) �> ( 1 2 4 5 8 )
18+
( 1 2 4 5 8 ) �> ( 1 2 4 5 8 )
19+
( 1 2 4 5 8 ) �> ( 1 2 4 5 8 )
20+
( 1 2 4 5 8 ) �> ( 1 2 4 5 8 )
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
*
3+
* Bubble sort implemented in a functional way i.e. Scala Style.
4+
* Scala encourages to implement solutions in recursive way.
5+
* It also gives flexibility of implementing solution in iterative way,
6+
* but pure scala style is in functional way.
7+
*
8+
*/
9+
object BubbleSort {
10+
11+
def bubbleSort(array: List[Int]) : List[Int] = {
12+
13+
def sort(pendingList: List[Int], sortedList: List[Int]) : List[Int] = {
14+
if(pendingList.isEmpty)
15+
sortedList
16+
else
17+
bubble(pendingList,Nil, sortedList)
18+
}
19+
20+
def bubble(pendingList: List[Int] , tempList: List[Int], sortedList: List[Int]) : List[Int] = {
21+
pendingList match {
22+
case h1 :: h2 :: t => {
23+
if(h1 > h2) bubble(h1 :: t, h2 :: tempList, sortedList)
24+
else bubble(h2 :: t, h1 :: tempList, sortedList)
25+
}
26+
case h1 :: Nil => sort(tempList, h1 :: sortedList)
27+
}
28+
}
29+
30+
sort(array, Nil)
31+
32+
}
33+
34+
35+
def main(args: Array[String]): Unit = {
36+
val x = bubbleSort(List(1,5,3,4,2))
37+
print(x)
38+
}
39+
40+
41+
}
42+

0 commit comments

Comments
 (0)