Created
July 24, 2017 05:48
-
-
Save taketimeasafriend/b056df40979ee3613c9f4f1960704aa4 to your computer and use it in GitHub Desktop.
14. 什么是数据结构? - 作业四
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'benchmark' | |
| def binary_search(arr, element) | |
| arr.sort! | |
| start_val = 0 | |
| end_val = arr.length - 1 | |
| while start_val <= end_val | |
| mid = start_val + (end_val - start_val) / 2; | |
| if arr[mid] < element | |
| start_val = mid + 1 | |
| elsif (arr[mid] > element) | |
| end_val = mid - 1 | |
| else | |
| return mid | |
| end | |
| end | |
| puts "not found." | |
| end | |
| arr = [0, 5, 13, 13, 30, 42, 52, 70, 85, 96, 103, 111, 116, 127, 130, 143, 150, 150, 161, 175, 207, 210, 218, 246, 257, 257, 263, 280, 304, 310, 326, 327, 332, 346, 360, 371, 374, 378, 406, 407, 407, 408, 428, 431, 437, 442, 445, 479, 489, 491, 505, 517, 520, 536, 548, 598, 602, 605, 618, 642, 649, 654, 659, 662, 677, 678, 682, 689, 695, 696, 697, 701, 711, 717, 727, 737, 745, 749, 754, 757, 770, 786, 802, 805, 814, 832, 840, 850, 853, 854, 888, 894, 904, 913, 913, 945, 962, 964, 972, 998] | |
| # 应该回传 35 | |
| puts arr.find_index(arr.bsearch {|x| x >= 371 }) | |
| puts binary_search(arr, 371).to_s | |
| Benchmark.bm do |x| | |
| x.report { | |
| binary_search(arr, 371) | |
| } | |
| x.report { | |
| arr.find_index(arr.bsearch {|x| x >= 371 }) | |
| } | |
| end | |
| arr1 = Array.new(10) { |param| param = rand(10)} # each 和 块 里面处理逻辑不太懂,尤其这个赋值,看书后理解的这样写,但是下面那样才简洁 | |
| arr2 = Array.new(10000) { rand(10000)} | |
| arr3 = Array.new(1000000) {rand(1000000)} | |
| puts binary_search(arr1, 9).to_s | |
| puts binary_search(arr2, 1234).to_s | |
| puts binary_search(arr3, 123456).to_s | |
| Benchmark.bm do |x| | |
| x.report { | |
| binary_search(arr1, 9) | |
| } | |
| x.report { | |
| binary_search(arr2,1234) | |
| } | |
| x.report { | |
| binary_search(arr3, 123456) | |
| } | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment