How to find the floor of N in a sorted array with C#

1 Answer

0 votes
using System;

// floor of N = the largest element in the array smaller than or equal to N

internal class Program
{
	private static int find_the_floor(int[] arr, int N) {
		int size = arr.Length;

		if (N >= arr[size - 1]) {
			return size - 1;
		}

		if (N < arr[0]) {
			return -1;
		}

		for (int i = 1; i < size; i++) {
			if (arr[i] > N) {
				return i - 1;
			}
		}

		return -1;
	}

	public static void Main(string[] args)
	{
		int[] arr = new int[] {1, 2, 7, 8, 14, 19, 20, 24, 28};
		int N = 17;

		int index = find_the_floor(arr, N);

		if (index == -1) {
			Console.Write("The floor doesn't exist in array");
		}
		else {
			Console.Write("The floor of " + N + " is " + arr[index]);
		}
	}
}




/*
run:
    
The floor of 17 is 14
        
*/

 



answered Jan 20, 2024 by avibootz

Related questions

1 answer 110 views
1 answer 102 views
1 answer 122 views
1 answer 100 views
1 answer 115 views
1 answer 112 views
1 answer 87 views
...