Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to merge two sorted arrays in Swift

1 Answer

0 votes
import Foundation

func mergeArrays(_ arr1: [Int], _ arr2: [Int]) -> [Int] {
    var merged: [Int] = []
    merged.reserveCapacity(arr1.count + arr2.count) // efficient preallocation
    var i = 0
    var j = 0

    // Merge while both arrays have elements
    while i < arr1.count && j < arr2.count {
        if arr1[i] < arr2[j] {
            merged.append(arr1[i])
            i += 1
        } else {
            merged.append(arr2[j])
            j += 1
        }
    }

    // Append remaining elements
    if i < arr1.count {
        merged.append(contentsOf: arr1[i...])
    }
    if j < arr2.count {
        merged.append(contentsOf: arr2[j...])
    }

    return merged
}


let arr1 = [1, 3, 5, 7, 8, 9, 9]
let arr2 = [2, 3, 4, 5, 6, 9]

let result = mergeArrays(arr1, arr2)
print(result)




/*
run:

[1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 9, 9]

*/

 



answered Nov 30, 2025 by avibootz
edited Dec 1, 2025 by avibootz

Related questions

...