Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a program that finds the index of given element in a sorted array
- // of integers by using the binary search algorithm (find it in Wikipedia).
- using System;
- class BinarySearch
- {
- static void Main()
- {
- Console.Write("Enter the array length: ");
- int length = int.Parse(Console.ReadLine());
- Console.Write("Enter the element to be found: ");
- int element = int.Parse(Console.ReadLine());
- int[] myArray = new int[length];
- for (int i = 0; i < length; i++)
- {
- Console.Write("Enter the Array1 Element[{0}]: ", i + 1);
- myArray[i] = int.Parse(Console.ReadLine());
- }
- int minValue = 0;
- int maxValue = myArray.Length;
- Array.Sort(myArray);
- BinarySearchMeth(minValue, maxValue, myArray, element);
- }
- static void BinarySearchMeth (int min, int max, int[] Array, int elementF)
- {
- int pivot = min/2 + max/2;
- if (Array[pivot] > elementF) max = pivot;
- else if (Array[pivot] < elementF) min = pivot;
- else if (Array[pivot] == elementF)
- {
- Console.WriteLine("The element has index {0} in the array", pivot);
- return;
- }
- if (min == max)
- {
- Console.WriteLine("There is no such element in the array");
- return;
- }
- if (min != max) BinarySearchMeth(min, max, Array, elementF);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement