Search and Sort

Search Algorithms

Searching: Processor of finding a target element within a group of items called the search pool.

Sequential Search Algorithm

Process:

Performance:

Example:

public static int sequentialSearch(int[] array, int value) {
    int index = 0;
    int element = -1;
    boolean found = false;
    while (!found && index < array.length) {
        if (array[index] == value) {
            found = true;
            element = index;
        }
        index++;
    }
    return element;
}

Process:

  1. Examine middle element of the list.
    1. If it matches the target, search is over.
    2. If not, remove either the top or bottom half (depending on which one the search target could be in)
      1. Go back to step 1 with the new, smaller list.

Performance:

Example:

public static int binarySearch(int[] array, int value)
{
    int first; last, middle, position;
    boolean found = false;
    first = 0;
    last = array.length - 1;
    position = -1;
    while (!found && first <= last) {
        middle = (first + last) / 2;
        if (array[middle] == value) {
            found = true;
            position = middle;
        }
        else if (array[middle] > value)
            last = middle - 1;
        else
            first = middle + 1;
    }
    return position;
}

When To Sort?

If you had to sort the data first, you have to look at all the data first (O(n)) before you can run efficient binary searches (O(\log n)).

Sorting

Sorting: Process of arranging a list of items in a particular order.

Selection Sort

Process:

  1. Find smallest value in array
  2. Switch smallest value with the value in the first position.
  3. Find next smallest value in array.
  4. Switch it with the value in the second position.
  5. Repeat until everything is sorted.

Efficiency:

Note on Swapping: Swapping requires 3 assignment statements and a temporary storage location.

Insertion Sort

Process:

  1. Consider the first item to be a sorted sublist (of one item)
  2. Insert the second item into the sorted sublist, shifting the first item as needed to make room to insert the new addition.
  3. Insert the third item into the sorted sublist (of two items), shifting items as necessary.
  4. Repeat until all values are inserted into their proper positions.

Efficiency:

Comparing Sorts

Selection and Insertion sort algorithms are similar in efficiency.