Software Development Techniques Topic 05: Selection

  • Selection let us provide branches of the flow of execution.
  • Only one kind of selection is discussed in this topic, but some languages have several types.
    • We call it an If then structure.
    • It can also have otherwise parts

Few questions to Practice

  1. A program takes whole number. Find whether it is greater than 100  or not.
  2. A program takes input from user to find what day is today. If today is Saturday, display “It is a happy holiday.” else “It is a Weekday”.
  3. Find whether user inputs positive or negative number.
  4. WAP to take monthly salary. If yearly salary is above 200,000 then display “You have to pay tax” otherwise display “You don’t have to pay tax.”
  5. Write a pseudo code to take age. If age is greater than 0, display “Valid age” otherwise display “Invalid age”. Also if age is above 17, display “You are eligible to vote.” otherwise “You are not eligible to vote”.

Binary Search

  • If we have an array that is in ascending or descending order, we can use a binary search.
    • We pick the mid-point of the array.
      • If we have found our search term, our work is done.
    • If the search term is not there, we split the array in two segments.
      • If our search term is higher than our current term, binary search the top half.
      • If our search term is lower than our current term, binary search the bottom half.
    • Continue until found, or until the term is not found.

The pseudo code of Binary Search is given below:

BinarySearch Pseudocode

The Java source code of Binary Search is given below:

BinarySearch Source code

Pseudo code and Java source code of Linear Search

Searching

  • Searching algorithms allow us to find a specific element in an array.
    • We often want to know if an element is present in an array before performing some operation.
  • If we are storing a list of names, we will want to check to make sure a name is not already there.
  • Searching algorithms allow us to do that.
    • And also, it can allow us to find out specifically where the element is if that is needed.

Linear Search

  • The simplest and most costly search is a linear search.
    • We start at the beginning of an array.
    • We check each element in turn to see if it is our desired element.
    • We continue until we get to the end.
  • Linear search is simple to code, and simple to understand.
  • But it also has performance issues.

The pseudo code of linear search using function is shown below:

Linear Search Pseudocode

The java source code of linear search using function is shown below:

Linear Search