Welcome to BigData School that can get you hired on Small startups or big Product based companies.Are you tired of 30-40 hours of theoritical bigdata courses in the market. Welcome to 240+ hours of Bigdata training. Just subscribe to our popup to get access to our 80+hours of course absolutely free.Try them out and you can join our further course once you are happy with our Demos.

Sort 2 sorted Array

Big Data    On Thursday 22nd of June 2017 12:10:06 PM By Suraz Ghimire
Given 2 sorted array, Your job is to create a third array, such that the third array will also be sorted.

Input
val arr1=Array(1,3,4,7,10)
val arr2=Array(2,3,6,7,7,12,15)

Output
val arr3= Array(1,2,3,4,4,6,7,7,7,10,12,15)

Code:
package sorting.sorting

object Merge2SortedArray {

def merge(arr1: Array[Int], arr2: Array[Int]): Unit ={
val arr=new Array[Int](arr1.length+arr2.length)
var index=0
var iCount=0
var jCount=0
var iConsumed=0
var jConsumed=0
import util.control.Breaks._

for (i <- 0 + iCount until arr1.length) {
breakable {
for (j <- 0 + jCount until arr2.length) {
println(s"Compare $i and $j")
if (arr1(i) < arr2(j)) {
println(s"${arr1(i)}< ${arr2(j)}, Store ${arr1(i)} in main array")
arr(index) = arr1(i)
index += 1
iConsumed=i
//iCount += 1
jCount=j
break
}else{
println(s"${arr1(i)}> ${arr2(j)}, Store ${arr2(j)} in main array")
arr(index) = arr2(j)
jConsumed=j
index += 1
}
}
}

}

println(iConsumed+"::"+jConsumed)

if(iConsumed+1<arr1.length){
val diff=arr1.length-iConsumed-1
var remainingFrom=arr.length-diff
for(i<-iConsumed+1 until arr1.length){
arr(remainingFrom)=arr1(i)
remainingFrom+=1
}
}

if(jConsumed+1<arr2.length){
val diff=arr2.length-jConsumed-1
var remainingFrom=arr.length-diff
for(i<-jConsumed+1 until arr2.length){
println(s"Arr($remainingFrom) ="+arr2(i))
arr(remainingFrom)=arr2(i)
remainingFrom+=1
}
}

arr.foreach(println)

}

def main(args: Array[String]): Unit = {
val arr1=Array(1,3,4,7,10)
val arr2=Array(2,3,6,7,7,12,15)

merge(arr1,arr2)
}

}


About Author

Suraz Ghimire