|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright (c) 2022, Silvio Peroni <essepuntato@gmail.com> |
| 3 | +# |
| 4 | +# Permission to use, copy, modify, and/or distribute this software for any purpose |
| 5 | +# with or without fee is hereby granted, provided that the above copyright notice |
| 6 | +# and this permission notice appear in all copies. |
| 7 | +# |
| 8 | +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH |
| 9 | +# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND |
| 10 | +# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, |
| 11 | +# OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, |
| 12 | +# DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS |
| 13 | +# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS |
| 14 | +# SOFTWARE. |
| 15 | + |
| 16 | + |
| 17 | +# Test case for the function |
| 18 | +def test_jump_search(olist, s, b, expected): |
| 19 | + result = jump_search(olist, s, b) |
| 20 | + |
| 21 | + if result == expected: |
| 22 | + return True |
| 23 | + else: |
| 24 | + return False |
| 25 | + |
| 26 | + |
| 27 | +# Code of the function |
| 28 | +def jump_search(olist, s, b): |
| 29 | + l_len = len(olist) |
| 30 | + |
| 31 | + for start in range(0, l_len, b): |
| 32 | + stop = start + b - 1 |
| 33 | + if stop >= l_len: |
| 34 | + stop = l_len - 1 |
| 35 | + |
| 36 | + if olist[stop] >= s: |
| 37 | + for idx in range(start, stop + 1): |
| 38 | + if olist[idx] == s: |
| 39 | + return idx |
| 40 | + |
| 41 | + return None |
| 42 | + |
| 43 | + return None |
| 44 | + |
| 45 | + |
| 46 | +# Tests |
| 47 | +print(test_jump_search([], 2, 3, None)) |
| 48 | +print(test_jump_search([1], 2, 3, None)) |
| 49 | +print(test_jump_search([2], 2, 3, 0)) |
| 50 | +print(test_jump_search([1, 2], 2, 3, 1)) |
| 51 | +print(test_jump_search([1, 2, 2, 4], 2, 3, 1)) |
| 52 | +print(test_jump_search([1, 2, 2, 4, 5], 5, 3, 4)) |
| 53 | +print(test_jump_search([1, 2, 2, 4, 5, 5], 5, 3, 4)) |
| 54 | +print(test_jump_search([1, 2, 2, 4, 5, 6], 6, 3, 5)) |
0 commit comments