Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

PAIR PROGRAMMING:

SHANTHAN REDDY – CB.EN,.U4CSE19459

SAI KOUSHIK – CB.EN.U4CSE19449

1.Insertion Sort:

SCALA:

object insertion_sort {
def main(args: Array[String]): Unit = {
var IntArray = Array(11, 15, 12, 14, 13)
var i: Int = 0
var j: Int = 0

var item: Int = 0

// Sort array using insertion sort in ascending order.


i = 1
while (i < 5) {
item = IntArray(i)
j = i - 1
while (j >= 0 && IntArray(j) > item) {
IntArray(j + 1) = IntArray(j);
j = j - 1;
}

IntArray(j + 1) = item;
i = i + 1
}

i = 0;
println("Sorted Array in ascending order: ");
while (i < 5) {
printf("%d ", IntArray(i));
i = i + 1;
}
println()
}
}
OUTPUT:

HASKELL:

insert_sorted :: [Int] -> Int -> [Int]


insert_sorted = \list -> \v ->
case list of
x:xs | v>x -> x:insert_sorted xs v
_ -> v:list

insertion_sort :: [Int] -> [Int]


insertion_sort = \list ->
case list of
[] -> []
x:xs -> insert_sorted (insertion_sort xs) x

main = print (insertion_sort [8, 9, 3, 4, 7])

OUTPUT:

2.Selection Sort:

SCALA:

class MySort()
{
// Swap the array element
def swap(arr: Array[Int], x: Int, y: Int): Unit = {
// x and y are index of array
var temp: Int = arr(x);
arr(x) = arr(y);
arr(y) = temp;
}
def selectionSort(arr: Array[Int], n: Int): Unit = {
var min: Int = 0;
var i: Int = 0;
// Execute loop from 0..n
while (i < n)
{
// Get current index
min = i;
var j: Int = i + 1;
while (j < n)
{
if (arr(min) > arr(j))
{
// Get the minimum element index
min = j;
}
j += 1;
}
if (i != min)
{
// Swap minimum element at i index
swap(arr, i, min);
}
i += 1;
}
}
// Display array elements
def display(arr: Array[Int], n: Int): Unit = {
var i: Int = 0;
while (i < n)
{
// Display element value
print(" " + arr(i));
i += 1;
}
print("\n");
}
}
object Main
{
def main(args: Array[String]): Unit = {
var task: MySort = new MySort();
// Array of integer elements
var arr: Array[Int] = Array( 8, 2, 3, 8, 1, 3, 73, 121, 54, 23, 84, 13,
67, 23, 52);
// Get the size of array
var n: Int = arr.length;
println(" Before Sort :");
task.display(arr, n);

task.selectionSort(arr, n);

println(" After Sort :");


task.display(arr, n);
}
}

OUTPUT:

HASKELL:

find_min :: [Int] -> Int


find_min = \list ->
case list of
[] -> error "List cannot be empty!"
[x] -> x
x:xs | x > find_min xs -> find_min xs
x:_ -> x

remove_one :: [Int] -> Int -> [Int]


remove_one = \list -> \v ->
case list of
[] -> error "Element not found!"
x:xs | v==x -> xs
x:xs -> x:remove_one xs v

selection_sort :: [Int] -> [Int]


selection_sort = \list ->
case list of
[] -> []
_ -> find_min list:selection_sort
(remove_one list (find_min list))

main = print (selection_sort [8, 9, 3, 4, 7])

OUTPUT:

You might also like