/// <summary> /// Find an estimated length and use regular binary search /// <para>Time Complexity: O(log(n))</para> /// <para>Space Complexity: O(log(n)) - recursion depth</para> /// </summary> /// <param name="list"></param> /// <param name="item"></param> /// <returns></returns> public static int SearchWithNoSize(Listy list, int item) { if (list == null) { return(-1); } // Find length - runtime O(log(n)) int index = 1; while (list.ElementAt(index) != -1 && list.ElementAt(index) < item) { index *= 2; } return(Search(list, item, index / 2, index)); }
private static int Search(Listy list, int item, int start, int end) { if (start > end) { return(-1); } int mid = (start + end) / 2; if (list.ElementAt(mid) == item) { return(mid); } else if (list.ElementAt(mid) > item || list.ElementAt(mid) == -1) { return(Search(list, item, start, mid - 1)); } else { return(Search(list, item, mid + 1, end)); } }
//10.4 Sorted Search, No Size: You are given an array like data structure Listy which lacks a size // method. It does, however, have an elementAt ( i) method that returns the element at index i in // 0( 1) time. If i is beyond the bounds of the data structure, it returns -1. (For this reason, the data // structure only supports positive integers.) Given a Li sty which contains sorted, positive integers, // find the index at which an element x occurs. If x occurs multiple times, you may return any index. public static int Search(Listy list, int value) { int index = 1; while (list.ElementAt(index) != -1 && list.ElementAt(index) < value) { index *= 2; } return(BinarySearch(index / 2, index)); int BinarySearch(int low, int high) { int mid; while (low <= high) { mid = (low + high) / 2; int middle = list.ElementAt(mid); if (middle > value && middle == -1) { high = mid - 1; } else if (middle < value) { low = mid + 1; } else { return(mid); } } return(-1); } }
/// <summary> /// Searches an array-like data structure that has no size method or property /// </summary> /// <param name="list"></param> /// <param name="key"></param> /// <returns></returns> public static int SearchListy(Listy <int> list, int key) { if (list == null || list.ElementAt(0) == -1) { return(-1); } int index = 1; while (list.ElementAt(index) != -1 && list.ElementAt(index) < key) { index *= 2; } int low = index / 2; int high = index; while (low < high) { int mid = (low + high) / 2; if (list.ElementAt(mid) == key) { return(mid); } else if (list.ElementAt(mid) == -1) { high = mid - 1; } else if (list.ElementAt(mid) < key) { low = mid + 1; } else if (list.ElementAt(mid) > key) { high = mid - 1; } } return(-1); }