What is an Algorithm?
An Algorithm is a finite, step-by-step procedure to solve a specific problem. In the world of Java programming, an algorithm is a logic that takes an input, processes it through defined steps, and produces the desired output.
Characteristics of a Good Algorithm:
- Input: It should have zero or more well-defined inputs.
- Output: It must produce at least one output.
- Definiteness: Each step must be clear and unambiguous.
- Finiteness: The algorithm must terminate after a finite number of steps.
- Effectiveness: Every step must be basic enough to be performed using a pen and paper.
Java Example: Linear Search Algorithm
public class AlgorithmDemo {
// A simple algorithm to find an element in an array
public static int search(int[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
return i; // Target found
}
}
return -1; // Target not found
}
}