查找算法

1、折半查找 

 1 // 递归算法

 2 int BinarySearch(int item, Node *elem, int left, int right)

 3 {

 4     int mid = -1;

 5     if(left <= right) {

 6         mid = (left + right) / 2;

 7         if(elem.val < item) 

 8             mid = BinarySearch(item, elem, (mid + 1), right);

 9         else if(elem.val > item)

10             mid = BinarySearch(item, elem, left, (mid - 1));

11     }

12     return mid;

13 }

14 

15 // 非递归算法

16 int BinarySearch(int item, Node *elem, int len)

17 {

18     int left = 0, right = len - 1, mid = -1;

19     while(left <= right) {

20         mid = (left + right) / 2;

21         if(elem.val < item)

22             left = mid + 1;

23         else if(elem.val > item)

24             right = mid - 1;

25         else

26             return mid;

27     }

28     return NOFOUND;

29 }
View Code

 

OK哒!O(∩_∩)O哈哈~

你可能感兴趣的:(算法)