A cooking recipe, the instructions for assembling flat-pack furniture and the route a satnav plans are all algorithms in the everyday sense: a precise sequence of steps that turns a starting situation into a result. In computing, the steps must be unambiguous enough for a machine to follow, and they must eventually finish. The same algorithm can be written in Python, Java or plain English; code is just one way of expressing it.
Example: binary search
Finding a name in a printed phone book is faster if you open it in the middle, decide which half the name must be in, and repeat. That idea is binary search, and it only works on sorted data:
static int find(int[] sorted, int target) {
int low = 0, high = sorted.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (sorted[mid] == target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1; // not found
}
On a sorted list of a million items, this needs at most about 20 checks. Reading items one by one, called linear search, could need a million.
Measuring efficiency
Programmers compare algorithms with Big O notation, which describes how the work grows as the input grows. Linear search is O(n), binary search is O(log n), and a simple nested-loop sort such as bubble sort is O(n²). For tiny inputs the difference hardly matters; for millions of records it decides whether a program responds instantly or takes hours.
Algorithm vs program
An algorithm is the idea, while a program is a concrete implementation in a specific language, along with everything else needed to run it, such as input handling and error checks. One algorithm can have many implementations. Algorithms also depend heavily on how data is organised, which is why they are usually studied alongside data structures like the array.
Keep learning
- Programming fundamentals
- Implement the search above in the Java editor
- Java course
Last updated