Find k closest numbers in an unsorted array

Here given code implementation process.

//C Program
//Find k closest numbers in an unsorted array
#include <stdio.h>

//Get difference of two elements
int difference(int arr[],int value,int index)
{
  if(value > arr[index])
  {
    return value-arr[index];
  }
  else
  {
    return arr[index]-value;
  }

}
void k_closest(int arr[],int size,int value,int k)
{
  if(size<=1 || k > size )
  {
    return;
  }

  int result[k];
  
  int diff=0,auxiliary=0,checker=0,old=0;
  
  for (int i = 0; i < k; ++i)
  {
    result[i]=i;
  }
 
  for (int i = k; i < size; ++i)
  {
    diff = difference(arr,value,i);
    checker=-1;
    for (int j = 0; j < k; ++j)
    {
      auxiliary = difference(arr,value,result[j]);

      if(auxiliary > diff)
      { 
        if(checker==-1)
        {
          checker=result[j];
        }
        else
        {
          old = difference(arr,value,checker);

          if(old < auxiliary)
          {
             checker=result[j];
          }

        }   
      }


    }
    if(checker!=-1)
    {
      result[checker]=i;
    }
  }

  for (int i = 0; i < k; ++i)
  {
    printf("Location %d : %d\n",result[i],arr[result[i]] );
  }
}

int main()
{
  //Defining collection array elements
  int arr[] = {1, 6, 4, 10, 2, 5};
  //Get the size of array
  int size=sizeof(arr)/sizeof(arr[0]);

  k_closest(arr,size,5,4);
  return 0;
}

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
/*
  C++ Program
  Find k closest numbers in an unsorted array
*/
#include<iostream>

using namespace std;

class MyArray {
	public:

		//Get difference of two elements
		int difference(int arr[], int value, int index) {
			if (value > arr[index]) {
				return value - arr[index];
			} else {
				return arr[index] - value;
			}
		}
	void k_closest(int arr[], int size, int value, int k) {
		if (size <= 1 || k > size) {
			return;
		}
		int result[k];
		int diff = 0, auxiliary = 0, checker = 0, old = 0;
		for (int i = 0; i < k; ++i) {
			result[i] = i;
		}
		for (int i = k; i < size; ++i) {
			diff = this->difference(arr, value, i);
			checker = -1;
			for (int j = 0; j < k; ++j) {
				auxiliary = this->difference(arr, value, result[j]);
				if (auxiliary > diff) {
					if (checker == -1) {
						checker = result[j];
					} else {
						old = this->difference(arr, value, checker);
						if (old < auxiliary) {
							checker = result[j];
						}
					}
				}
			}
			if (checker != -1) {
				result[checker] = i;
			}
		}
		for (int i = 0; i < k; ++i) {
			cout << "Location " << result[i] << " : " << arr[result[i]] << "\n";
		}
	}
};
int main() {
	MyArray obj ;
	int arr[] = {
		1,
		6,
		4,
		10,
		2,
		5
	};
	//Count size of array
	int size = sizeof(arr) / sizeof(arr[0]);
	obj.k_closest(arr, size, 5, 4);
	return 0;
}

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
/*
  Java Program
  Find k closest numbers in an unsorted array
*/
public class MyArray {

  //Get difference of two elements
  public int difference(int []arr,int value,int index)
  {
    if(value > arr[index])
    {
      return value-arr[index];
    }
    else
    {
      return arr[index]-value;
    }

  }
  public void k_closest(int []arr,int size,int value,int k)
  {
    if(size<=1 || k > size )
    {
      return;
    }

    int []result = new int[k];
    
    int diff=0,auxiliary=0,checker=0,old=0;
    
    for (int i = 0; i < k; ++i)
    {
      result[i]=i;
    }
   
    for (int i = k; i < size; ++i)
    {
      diff = difference(arr,value,i);
      checker=-1;
      for (int j = 0; j < k; ++j)
      {
        auxiliary = difference(arr,value,result[j]);

        if(auxiliary > diff)
        { 
          if(checker==-1)
          {
            checker=result[j];
          }
          else
          {
            old = difference(arr,value,checker);

            if(old < auxiliary)
            {
               checker=result[j];
            }

          }   
        }


      }
      if(checker!=-1)
      {
        result[checker]=i;
      }
    }

    for (int i = 0; i < k; ++i)
    {
      System.out.print("Location "+result[i]+" : "+arr[result[i]]+"\n");
    }
  }

  public static void main(String[] args) 
  {

    MyArray obj = new MyArray();
    //Define array elements
    int []arr = {1, 6, 4, 10, 2, 5};
    //Count size of array
    int size=arr.length;
 

    obj.k_closest(arr,size,5,4);

  }
}

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
using System;

/*
  C# Program
  Find k closest numbers in an unsorted array
*/

public class MyArray {
	//Get difference of two elements
	public int difference(int[] arr, int value, int index) {
		if (value > arr[index]) {
			return value - arr[index];
		} else {
			return arr[index] - value;
		}
	}
	public void k_closest(int[] arr, int size, int value, int k) {
		if (size <= 1 || k > size) {
			return;
		}
		int[] result = new int[k];
		int diff = 0, auxiliary = 0, checker = 0, old = 0;
		for (int i = 0; i < k; ++i) {
			result[i] = i;
		}
		for (int i = k; i < size; ++i) {
			diff = difference(arr, value, i);
			checker = -1;
			for (int j = 0; j < k; ++j) {
				auxiliary = difference(arr, value, result[j]);
				if (auxiliary > diff) {
					if (checker == -1) {
						checker = result[j];
					} else {
						old = difference(arr, value, checker);
						if (old < auxiliary) {
							checker = result[j];
						}
					}
				}
			}
			if (checker != -1) {
				result[checker] = i;
			}
		}
		for (int i = 0; i < k; ++i) {
			Console.Write("Location " + result[i] + " : " + arr[result[i]] + "\n");
		}
	}
	public static void Main(String[] args) {
		MyArray obj = new MyArray();
		int[]
		//Define array elements
		arr = {
			1,
			6,
			4,
			10,
			2,
			5
		};
		//Count size of array
		int size = arr.Length;
		obj.k_closest(arr, size, 5, 4);
	}
}

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
<?php
/*
  Php Program
  Find k closest numbers in an unsorted array
*/
class MyArray {
	//Get difference of two elements

	public 	function difference($arr, $value, $index) {
		if ($value > $arr[$index]) {
			return $value - $arr[$index];
		} else {
			return $arr[$index] - $value;
		}
	}
	public 	function k_closest($arr, $size, $value, $k) {
		if ($size <= 1 || $k > $size) {
			return;
		}
		$result = array_fill(0, $k, 0);
		$diff = 0;
		$auxiliary = 0;
		$checker = 0;
		$old = 0;
		for ($i = 0; $i < $k; ++$i) {
			$result[$i] = $i;
		}
		for ($i = $k; $i < $size; ++$i) {
			$diff = $this->difference($arr, $value, $i);
			$checker = -1;
			for ($j = 0; $j < $k; ++$j) {
				$auxiliary = $this->difference($arr, $value, $result[$j]);
				if ($auxiliary > $diff) {
					if ($checker == -1) {
						$checker = $result[$j];
					} else {
						$old = $this->difference($arr, $value, $checker);
						if ($old < $auxiliary) {
							$checker = $result[$j];
						}
					}
				}
			}
			if ($checker != -1) {
				$result[$checker] = $i;
			}
		}
		for ($i = 0; $i < $k; ++$i) {
			echo("Location ". $result[$i] ." : ". $arr[$result[$i]] ."\n");
		}
	}
}

function main() {
	$obj = new MyArray();
	//Define array elements
	$arr = array(1, 6, 4, 10, 2, 5);
	//Count size of array
	$size = count($arr);
	$obj->k_closest($arr, $size, 5, 4);

}
main();

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
/*
  Node Js Program
  Find k closest numbers in an unsorted array
*/
class MyArray {
	//Get difference of two elements
	difference(arr, value, index) {
		if (value > arr[index]) {
			return value - arr[index];
		} else {
			return arr[index] - value;
		}
	}
	k_closest(arr, size, value, k) {
		if (size <= 1 || k > size) {
			return;
		}
		var result = Array(k).fill(0);
		var diff = 0;
		var auxiliary = 0;
		var checker = 0;
		var old = 0;
		for (var i = 0; i < k; ++i) {
			result[i] = i;
		}

		for (var i = k; i < size; ++i) {
			diff = this.difference(arr, value, i);
			checker = -1;
			for (var j = 0; j < k; ++j) {
				auxiliary = this.difference(arr, value, result[j]);
				if (auxiliary > diff) {
					if (checker == -1) {
						checker = result[j];
					} else {
						old = this.difference(arr, value, checker);
						if (old < auxiliary) {
							checker = result[j];
						}
					}
				}
			}

			if (checker != -1) {
				result[checker] = i;
			}
		}

		for (var i = 0; i < k; ++i) {
			process.stdout.write("Location " + result[i] + " : " + arr[result[i]] + "\n");
		}
	}
}

function main(args) {
	var obj = new MyArray();
	//Define array elements
	var arr = [1, 6, 4, 10, 2, 5];
	//Count size of array
	var size = arr.length;
	obj.k_closest(arr, size, 5, 4);
}

main();

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
# Python 3 Program
# Find k closest numbers in an unsorted array
class MyArray :
	# Get difference of two elements
	def difference(self, arr, value, index) :
		if (value > arr[index]) :
			return value - arr[index]
		else :
			return arr[index] - value
		
	
	def k_closest(self, arr, size, value, k) :
		if (size <= 1 or k > size) :
			return
		
		result = [0] * k
		diff = 0
		auxiliary = 0
		checker = 0
		old = 0
		i = 0
		while (i < k) :
			result[i] = i
			i += 1
		
		i = k
		while (i < size) :
			diff = self.difference(arr, value, i)
			checker = -1
			j = 0
			while (j < k) :
				auxiliary = self.difference(arr, value, result[j])
				if (auxiliary > diff) :
					if (checker == -1) :
						checker = result[j]
					else :
						old = self.difference(arr, value, checker)
						if (old < auxiliary) :
							checker = result[j]
						
					
				
				j += 1
			
			if (checker != -1) :
				result[checker] = i
			
			i += 1
		
		i = 0
		while (i < k) :
			print("Location ", result[i] ," : ", arr[result[i]] ,"\n", end = "")
			i += 1
		
	

def main() :
	obj = MyArray()
	arr = [1, 6, 4, 10, 2, 5]
	size = len(arr)
	obj.k_closest(arr, size, 5, 4)


if __name__ == "__main__":
	main()

Output

Location  5  :  5
Location  1  :  6
Location  2  :  4
Location  4  :  2
# Ruby Program
# Find k closest numbers in an unsorted array
class MyArray 
	# Get difference of two elements
	def difference(arr, value, index) 
		if (value > arr[index]) 
			return value - arr[index]
		else 
			return arr[index] - value
		end
	end
	def k_closest(arr, size, value, k) 
		if (size <= 1 || k > size) 
			return
		end
		result = Array.new(k, 0)
		diff = 0
		auxiliary = 0
		checker = 0
		old = 0
		i = 0
		while (i < k) 
			result[i] = i
			i += 1
		end
		i = k
		while (i < size) 
			diff = self.difference(arr, value, i)
			checker = -1
			j = 0
			while (j < k) 
				auxiliary = self.difference(arr, value, result[j])
				if (auxiliary > diff) 
					if (checker == -1) 
						checker = result[j]
					else 
						old = self.difference(arr, value, checker)
						if (old < auxiliary) 
							checker = result[j]
						end
					end
				end
				j += 1
			end
			if (checker != -1) 
				result[checker] = i
			end
			i += 1
		end
		i = 0
		while (i < k) 
			print("Location ", result[i] ,"  : ", arr[result[i]] ,"\n")
			i += 1
		end
	end
end
def main() 
	obj = MyArray.new()
	arr = [1, 6, 4, 10, 2, 5]
	size = arr.length
	obj.k_closest(arr, size, 5, 4)
end
main()

Output

Location 5  : 5
Location 1  : 6
Location 2  : 4
Location 4  : 2
/*
  Scala Program
  Find k closest numbers in an unsorted array
*/
class MyArray {
	//Get difference of two elements
	def difference(arr: Array[Int], value: Int, index: Int): Int = {
		if (value > arr(index)) {
			return value - arr(index);
		} else {
			return arr(index) - value;
		}
	}
	def k_closest(arr: Array[Int], size: Int, value: Int, k: Int): Unit = {
		if (size <= 1 || k > size) {
			return;
		}
		var result: Array[Int] = Array.fill[Int](k)(0);
        var diff: Int = 0;
        var auxiliary: Int = 0;
        var checker: Int = 0;
        var old: Int = 0;
        var i: Int = 0;
        while (i < k) {
            result(i) = i;
            i += 1;
        }
        i = k;
        while (i < size) {
            diff = this.difference(arr, value, i);
            checker = -1;
            var j: Int = 0;
            while (j < k) {
                auxiliary = this.difference(arr, value, result(j));

                if (auxiliary > diff) {
                    if (checker == -1) {
                        checker = result(j);
                    } else {
                        old = this.difference(arr, value, checker);

                        if (old < auxiliary) {
                            checker = result(j);
                        }
                    }
                }
                j += 1;
            }
            if (checker != -1) {
                result(checker) = i;
            }
            i += 1;
        }
        i = 0;
        while (i < k) {
            print("Location " + result(i) + " : " + arr(result(i)) + "\n");
            i += 1;
        }
    }
}
object Main {
	def main(args: Array[String]): Unit = {
		val obj: MyArray = new MyArray();
		val arr: Array[Int] = Array(1, 6, 4, 10, 2, 5);
		val size: Int = arr.length;
		obj.k_closest(arr, size, 5, 4);
	}
}

Output

Location 5 : 5
Location 1 : 6
Location 2 : 4
Location 4 : 2
/*
  Swift Program
  Find k closest numbers in an unsorted array
*/
class MyArray {
	//Get difference of two elements
	func difference(_ arr: [Int], _ value: Int, _ index: Int) -> Int {
		if (value > arr[index]) {
			return value - arr[index];
		} else {
			return arr[index] - value;
		}
	}
	func k_closest(_ arr: [Int], _ size: Int, _ value: Int, _ k: Int) {
		if (size <= 1 || k > size) {
			return;
		}
		var result: [Int] = Array(repeating: 0, count: k);
        var diff: Int = 0;
        var auxiliary: Int = 0;
        var checker: Int = 0;
        var old: Int = 0;
        var i: Int = 0;
        while (i < k) {
            result[i] = i;
            i += 1;
        }
        i = k;
        while (i < size) {
            diff = self.difference(arr, value, i);
            checker = -1;
            var j: Int = 0;
            while (j < k) {
                auxiliary = self.difference(arr, value, result[j]);
                if (auxiliary > diff) {
                    if (checker == -1) {
                        checker = result[j];
                    } else {
                        old = self.difference(arr, value, checker);
                        if (old < auxiliary) {
                            checker = result[j];
                        }
                    }
                }
                j += 1;
            }
            if (checker != -1) {
                result[checker] = i;
            }
            i += 1;
        }
        i = 0;
        while (i < k) {
            print("Location ", result[i] ," : ", arr[result[i]] ,"\n", terminator: "");
            i += 1;
        }
    }
}
func main() {
	let obj: MyArray = MyArray();
	let arr: [Int] = [1, 6, 4, 10, 2, 5];
	let size: Int = arr.count;
	obj.k_closest(arr, size, 5, 4);
}
main();

Output

Location  5  :  5
Location  1  :  6
Location  2  :  4
Location  4  :  2


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved