How to find the k closest elements to a giving value in sorted array with C#

1 Answer

0 votes
using System;

internal class Program
{
	private static void findKClosestElements(int[] arr, int k, int value) {
		int left = 0;
		int right = arr.Length - 1;

		while (right - left >= k) {
			if (Math.Abs(arr[left] - value) > Math.Abs(arr[right] - value)) {
				left++;
			}
			else {
				right--;
			}
		}

		while (left <= right) {
			Console.Write(arr[left] + " ");
			left++;
		}
	}

	public static void Main(string[] args)
	{
		int[] arr = new int[] {6, 10, 12, 15, 17, 18, 20, 25, 28};
		int value = 16, k = 4;

		findKClosestElements(arr, k, value);
	}
}




/*
run:

12 15 17 18 

*/

 



answered Jan 21, 2024 by avibootz
...