mathonsunday
11/17/2018 - 11:51 PM

Getting slice of multidimensional array


/*
 * Complete the mergeArrays function below.
 */
func mergeArrays(arr: [[Int]]) -> [Int] {
     guard arr.count > 1 else {
         return arr[0]
     }
     let mid = arr.count / 2
     var leftMultidimensionalArray = [[Int]]()
     for x in 0..<mid {
         leftMultidimensionalArray.append(arr[x])
     }
     var rightMultidimensionalArray = [[Int]]()
     for x in mid..<arr.count {
         rightMultidimensionalArray.append(arr[x])
     }
     let leftArray = mergeArrays(arr: leftMultidimensionalArray)
     let rightArray = mergeArrays(arr: rightMultidimensionalArray)
     return merge(leftArray, rightArray)
}

func merge(_ leftArray: [Int], _ rightArray: [Int]) -> [Int] {
    var leftArrayIndex = 0
    var rightArrayIndex = 0
    var mergeSortedArray: [Int] = []
    
    while leftArrayIndex < leftArray.count && rightArrayIndex < rightArray.count {
        let leftArrayValue = leftArray[leftArrayIndex]
        let rightArrayValue = rightArray[rightArrayIndex]
        
        if leftArrayValue < rightArrayValue {
            mergeSortedArray.append(leftArrayValue)
            leftArrayIndex += 1
        } else if leftArrayValue > rightArrayValue {
            mergeSortedArray.append(rightArrayValue)
            rightArrayIndex += 1 
        } else {
            mergeSortedArray.append(leftArrayValue)
            leftArrayIndex += 1 
            mergeSortedArray.append(rightArrayValue)
            rightArrayIndex += 1 
        }
    }
        
        if leftArrayIndex < leftArray.count {
            mergeSortedArray.append(contentsOf: leftArray[leftArrayIndex...])
        }
        if rightArrayIndex < rightArray.count {
            mergeSortedArray.append(contentsOf: rightArray[rightArrayIndex...])
        }
        
        return mergeSortedArray
    }