/// <summary> /// The entry point of the program. /// </summary> private static void Main() { try { int[] array = new int[] { 3, -1, 15, 4, 17, 2, 33, 0 }; Console.WriteLine("array = [{0}]", string.Join(", ", array)); ArrayUtils.SelectionSort(array); Console.WriteLine("sorted = [{0}]", string.Join(", ", array)); // Test sorting empty array ArrayUtils.SelectionSort(new int[0]); // Test sorting single element array ArrayUtils.SelectionSort(new int[1]); Console.WriteLine(ArrayUtils.BinarySearch(array, -1000)); Console.WriteLine(ArrayUtils.BinarySearch(array, 0)); Console.WriteLine(ArrayUtils.BinarySearch(array, 17)); Console.WriteLine(ArrayUtils.BinarySearch(array, 10)); Console.WriteLine(ArrayUtils.BinarySearch(array, 1000)); } catch (ArgumentNullException anex) { Console.WriteLine(anex.Message); } catch (ArgumentException aex) { Console.WriteLine(aex.Message); } }
public void TestBinarySearch() { int[] inputArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int key = 8; int expectedIndex = 7; int output = ArrayUtils.BinarySearch(inputArr, 0, inputArr.Length - 1, key); Assert.True(output == expectedIndex); }
//Search an element in a sorted and rotated array public int SearchRotatedArray(int[] arr, int elem) { //get pivot int pivot = GetPivot(arr, 0, arr.Length - 1); //search left array of pivot using binary search if (arr[pivot] == elem) { return(pivot); } if (arr[0] < elem) { return(ArrayUtils.BinarySearch(arr, 0, pivot - 1, elem)); } //search right array of pivot using binary search return(ArrayUtils.BinarySearch(arr, pivot + 1, arr.Length - 1, elem)); }