Exemplo n.º 1
0
        private static int BinarySearch <T>(T[] arr, T value, int startIndex, int endIndex)
            where T : IComparable <T>
        {
            Debug.Assert(arr.Length > 0, "Array is empty.");
            Debug.Assert(TestAssistant.IsSorted(arr), "Array is not sorted");

            while (startIndex <= endIndex)
            {
                int midIndex = (startIndex + endIndex) / 2;
                if (arr[midIndex].Equals(value))
                {
                    return(midIndex);
                }

                if (arr[midIndex].CompareTo(value) < 0)
                {
                    // Search on the right half
                    startIndex = midIndex + 1;
                }
                else
                {
                    // Search on the right half
                    endIndex = midIndex - 1;
                }
            }

            // Searched value not found
            Debug.Assert(Array.Exists(arr, element => element.CompareTo(value) == 0) == false, "Array contains wanted value but search returns -1.");

            return(-1);
        }
Exemplo n.º 2
0
        private static int FindMinElementIndex <T>(T[] arr, int startIndex, int endIndex)
            where T : IComparable <T>
        {
            Debug.Assert(arr.Length > 0, "Empty array.");
            Debug.Assert(arr.Length <= int.MaxValue, "Length of array is too big.");
            Debug.Assert(startIndex >= 0, "Start index is not greater than or equal to 0.");
            Debug.Assert(endIndex > 0, "End index is not greater than 0.");
            Debug.Assert(startIndex < endIndex, "End index is not greater than start index.");

            int minElementIndex = startIndex;

            for (int i = startIndex + 1; i <= endIndex; i++)
            {
                if (arr[i].CompareTo(arr[minElementIndex]) < 0)
                {
                    minElementIndex = i;
                }
            }

            Debug.Assert(TestAssistant.GetMinValue(arr, startIndex, endIndex).CompareTo(arr[minElementIndex]) == 0, "minElementIndex is not the index of min value.");

            return(minElementIndex);
        }