二进制搜索圆弧旋转数组

编程入门 行业动态 更新时间:2024-10-11 13:31:01
本文介绍了二进制搜索圆弧旋转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试执行二进制搜索以在循环排序的数组中查找元素.我收到一个我似乎不理解的类型错误.任何建议/修改将不胜感激.

I am trying to execute a Binary search to find an element in a circularly sorted array. I get a type error that I don't seem to understand. Any suggestions/modifications will be appreciated.

这是我的代码:

def Binarysearch(a, low, high, x): if low > high: return -1 else: mid = (low + high)/2 if x == a[mid]: return mid elif a[mid] <= a[high]: if x > a[mid] and x <= a[high]: return Binarysearch(a, mid+1, high, x) elif a[mid] >= a[low]: if x >= a[low] and x < a[mid]: return Binarysearch(a, low, mid-1, x) elem_list = [6, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5] x = int(raw_input('enter search elemet')) lenlist = len(elem_list) result = Binarysearch(elem_list, 0, lenlist-1, x) if result == -1: print "Not found" else: print "Found it", elem_list[result]

我收到错误消息:

Line32: TypeError: list indices must be integers, not NoneType

推荐答案

def rotated_binary_search(A, N, key): L = 0 R = N - 1 while (L <= R): M = L + ((R - L) / 2) if (A[M] == key): return M # the bottom half is sorted if (A[L] <= A[M]): if (A[L] <= key and key < A[M]): R = M - 1 else: L = M + 1 # the upper half is sorted else: if (A[M] < key and key <= A[R]): L = M + 1 else: R = M - 1 return -1 A = [6, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5] N = len(A) result = rotated_binary_search(A, N, 13) print "Original List", A if result == -1: print "Not found" else: print "Found", A[result], "at position", result`enter code here`

结果:

Original List [6, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5] Found 13 at position 3

更多推荐

二进制搜索圆弧旋转数组

本文发布于:2023-11-30 07:01:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649102.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:圆弧   数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!