Bash Script Binary Search

后端 未结 4 1175
闹比i
闹比i 2020-11-30 15:47

Write a bash script to do a binary search. Read student names and grades from a file into an array. Prompt the user for a student name. Find the name in the array and displa

4条回答
  •  半阙折子戏
    2020-11-30 16:07

    I think it's best to use a generic binary search function then to code your own for your particular case.

    Binary search function in bash

    # Returns the largest i for which `command i` succeeds (exits with a null exit code)
    function dichotomic_search {
    
      min=$1
      max=$2
      command=$3
    
      while [ $min -lt $max ]; do
        # Compute the mean between min and max, rounded up to the superior unit
        current=`expr '(' "$min" + "$max" + 1 ')' / 2`
        if $command $current
          then min=$current
          else max=`expr $current - 1`
        fi
      done
    
      echo $min
    }
    

    It calls the function given as its last argument repetitively using binary search to find the last value for which it returns true. More explanations on Github

    Binary search through a bash array

    In your case, you would use it like that:

    #!/usr/bin/env bash
    
    source dichotomic.sh
    arr=(Ann:C Bob:A Cindy:B Dean:E Emily:A Karen:A Zob:A)
    
    function is_smaller {
      element=$(echo ${arr[$2]} | cut -f1 -d :)
      if [[ "$element" > "$1" ]]
        then false
        else true
      fi
    }
    
    read target
    highest_index=`expr ${#arr[@]} - 1`
    index=$(dichotomic_search 0 $highest_index "is_smaller $target")
    echo "${arr[$index]}"
    

提交回复
热议问题