Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
849 B

4 years ago
  1. import math
  2. def jumpSearch( arr , x ):
  3. # Finding block size to be jumped
  4. n = len(arr)
  5. step = math.sqrt(n)
  6. # Finding the block where element is
  7. # present (if it is present)
  8. prev = 0
  9. while arr[int(min(step, n)-1)] < x:
  10. prev = step
  11. step += math.sqrt(n)
  12. if prev >= n:
  13. return -1
  14. # Doing a linear search for x in
  15. # block beginning with prev.
  16. while arr[int(prev)] < x:
  17. prev += 1
  18. # If we reached next block or end
  19. # of array, element is not present.
  20. if prev == min(step, n):
  21. return -1
  22. # If element is found
  23. if arr[int(prev)] == x:
  24. return int(prev)
  25. return -1
  26. arr = [ 0, 1, 3, 4, 4, 5, 8, 13, 22, 24, 55, 59, 122, 213, 422, 555 ]
  27. x = 55
  28. index = jumpSearch(arr, x)
  29. print("Number is at index {}".format(index))