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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

How to find the floor and ceiling of the value N in an unsorted array with Swift

1 Answer

0 votes
import Foundation

// Finds the floor and ceil of N in the given array
func findFloorAndCeil(arr: [Int], N: Int) -> (floor: Int, ceil: Int) {
    var floorval = Int.min // Initialize to smallest possible value
    var ceilval = Int.max  // Initialize to largest possible value

    for num in arr {
        if num <= N && num > floorval {
            floorval = num // Update floorval if num is closer to N
        }
        if num >= N && num < ceilval {
            ceilval = num // Update ceilval if num is closer to N
        }
    }

    // If no valid floorval or ceilval is found, set them to a special value
    if floorval == Int.min {
        floorval = -1
    }
    if ceilval == Int.max {
        ceilval = -1
    }

    return (floorval, ceilval)
}

let arr = [4, 10, 8, 2, 6, 9, 1]
let N = 5

let (floorval, ceilval) = findFloorAndCeil(arr: arr, N: N)

print("floor: \(floorval == -1 ? "None" : "\(floorval)")")
print("ceil: \(ceilval == -1 ? "None" : "\(ceilval)")")



/*
run:

floor: 4
ceil: 6

*/

 



answered Nov 8, 2025 by avibootz
...