|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Text; |
| 4 | + |
| 5 | +namespace Algorithms.NET.Searching.TernarySearch |
| 6 | +{ |
| 7 | + public class TernarySearchAlgorithm |
| 8 | + { |
| 9 | + /// <summary> |
| 10 | + /// Search an item in a list using TernarySearch algorithm, Time complexity of O(log3 n). |
| 11 | + /// </summary> |
| 12 | + /// <param name="item">Item to search for</param> |
| 13 | + /// <param name="sortedList">Sorted list in which we want to search.</param> |
| 14 | + /// <returns>Index of item if found, Otherwise returns -1.</returns> |
| 15 | + public static int Search(double item,List<double> sortedList) |
| 16 | + { |
| 17 | + return Search(sortedList,item,0,sortedList.Count - 1); |
| 18 | + } |
| 19 | + |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// Search an item in a list using TernarySearch algorithm in recursive approach, Time complexity of O(log3 n). |
| 23 | + /// </summary> |
| 24 | + /// <param name="item">Item to search for</param> |
| 25 | + /// <param name="sortedList">Sorted list in which we want to search.</param> |
| 26 | + /// <param name="endIndex">End index of searching.</param> |
| 27 | + /// <param name="startIndex">Start index of searching.</param> |
| 28 | + /// <returns>Index of item if found, Otherwise returns -1.</returns> |
| 29 | + private static int Search(List<double> sortedList,double item,int startIndex,int endIndex) |
| 30 | + { |
| 31 | + if (startIndex > endIndex) |
| 32 | + return -1; |
| 33 | + |
| 34 | + int partitionSize = (endIndex - startIndex) / 3; |
| 35 | + int m1 = partitionSize + startIndex; |
| 36 | + int m2 = endIndex - partitionSize; |
| 37 | + |
| 38 | + if (item == sortedList[m1]) |
| 39 | + return m1; |
| 40 | + if (item == sortedList[m2]) |
| 41 | + return m2; |
| 42 | + |
| 43 | + if(item < m1) |
| 44 | + return Search(sortedList, item, startIndex, m1 - 1); |
| 45 | + if (item > m1 && item < m2) |
| 46 | + return Search(sortedList, item, m1 + 1,m2 - 1); |
| 47 | + |
| 48 | + return Search(sortedList, item, m2 + 1, endIndex); |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments