In computer programming, an algorithm is a defined set of instructions that a computer should use to solve a specific problem or perform a computation.
The purpose of every computer program is to solve a problem, and in trying to solve the ultimate problem, the programmer would encounter other more minor problems along the way.
Writing a good algorithm involves the programmer breaking down a problem into smaller parts and finding out how to solve each part with code.
How To Write An Algorithm
Algorithms play a central role in manipulating data structures used in programs. Before transferring an algorithm to code, you should express it in human-readable form. You can write algorithms in three ways:
1. Natural language
You can write algorithms in common words and phrases in any human language you understand. In place of comparison operators, you can use words like equal to, lesson than, greater than, etc. You can write control structures using phrases like if, while, exit, and repeat for, and arithmetic operations using add, subtract, multiply, and divide.
2. Pseudocode
Describing an algorithm in human language can make it wordy, resulting in the algorithm becoming ambiguous. An alternative means of writing the algorithm is through the use of pseudocode. A pseudocode is a mixture of natural language and programming notation; it resembles a simplified programming language.
There are no universal conventions guiding pseudocode usage; however, they are always easily translated to programming languages.
3. Flow charts
A flow chart is a diagram consisting of shapes and arrows that can represent an algorithm or process. Flow charts are ideal for control statement algorithms.
Types And Uses Of Algorithms
Algorithms are an essential part of computer programming, and various algorithms can serve different purposes. Below are some types of algorithms and their uses:
1. Searching Algorithms
Searching algorithms are useful for locating or retrieving an element within a data structure. You can also use it to determine the presence of an element in a data structure.
Search algorithms can be sequential or interval; a sequential search goes through every element in the data set, while interval searches do not need to do that. Interval searches are more efficient than sequential search algorithms; however, you can only use them for sorted data sets.
Some types of searching algorithms are
- Linear Search
- Binary Search
- Fibonacci Search
- Exponential Search
- Jump Search
- Interpolation Search
- Sublist Search (Search a linked list in another list)
- The Ubiquitous Binary Search
2. Sorting Algorithms
A sorting algorithm is an algorithm that arranges elements of a list in a particular order. The sorting algorithm requires you to set the order you want the rearranged list to be in, the most common of which are ascending and descending order.
Every good sorting algorithm must output all elements in a monotonic order while ensuring that none of the original elements are lost. Sorting algorithms work faster on data structures that allow random access. There are many types of sorting algorithms, some of which are:
- Quicksort
- Merge sort
- Insertion sort
- Pigeonhole Sort
- Cycle Sort
- Cocktail Sort
- Gnome Sort
- Sleep Sort
3. Compression Algorithms
Compression algorithms compress a file to make its size more portable. Generally, when people speak of data compression, the concept also deals with data decompression. Compression algorithms will not work without a means of decompression because a compressed file needs decompression before you can use it.
The two main types of compression algorithms are lossless and lossy compression. Lossless compression involves compressing data to restore it to its exact state before compression, while lossy compression might involve some data loss.
Some programmers favor lossy compression algorithms because they compress data more than lossless compression. You can use lossy compression on files in which the loss of small bits of data doesn’t matter (like music, videos, and pictures). However, continuous lossy compression on a particular file can significantly decrease its quality.
4. Encryption Algorithms
An encryption algorithm is a means of converting data into an unintelligible format known as a cipher. Encryption algorithms need a key to decrypt the encrypted data into its original form. Encryption algorithms are an essential part of computer security and are used mainly in cyber security, where attacks from hackers occur regularly.
There are two broad categories of encryption algorithms– symmetric and asymmetric systems. In a symmetric key system, everyone accessing the data has the same key, and the key has to be known only to its owners. An asymmetric key system uses a public and private key; the private key is a secret, while the public key is made available to anyone who needs it. Both keys in an asymmetric system are mathematically tied together, and you cannot decrypt the data without using the two.
Some common encryption algorithms are:
- Triple Data Encryption Standard (DES)
- Advanced Encryption Standard (AES)
- Rivest-Shamir-Adleman (RSA) algorithm
- Blowfish
- Twofish
- Elliptic curve cryptography
5. Geometric Algorithms
Geometric algorithms help identify geometric shapes and solve geometric problems. Writing an excellent geometric algorithm requires you to have a strong background in various aspects of mathematics.
6. String Matching Algorithms
String matching algorithms are algorithms used to search for the location of several strings (or patterns) within another string. In string matching algorithms, the string you want to search is called the haystack, and the word you’re looking for is the needle. You can add constraints to the requirements of the needle to tailor your search to specific needs.
There are various types of string matching algorithms; some are:
- Naive Pattern Searching
- KMP Algorithm
- Rabin-Karp Algorithm
- Aho-Corasick Algorithm for Pattern Searching
- Suffix Array
- Trigram search
String matching algorithms are also known as pattern searching/matching or string matching algorithms.
Classification Of Algorithms
Algorithms in programming are classified based on the strategy used to solve a given problem. Some classification of algorithms are as follows:
1. Brute Force Algorithms
A brute force algorithm is the most straightforward possible algorithm; it involves using the first solution that you can get. After you get a solution using the brute force approach, you can further work on making the algorithm more efficient. Every programming problem can be solved using a brute force algorithm; however, they take more time and computer resources.
2. Iterative Algorithms
Iterative algorithms involve repeating specific steps in loops until the problem is solved. Iterative algorithms use an initial value to generate a sequence of improving approximate solutions for the problem. The most common use of iterative algorithms is to sort small data sets.
3. Divide-And-Conquer Algorithms
A divide-and-conquer algorithm fragments a given problem into small sets of sub-problems that are partially solved. The algorithm is used recursively and terminated when there can be no further divisions. Divide-and-conquer algorithms are the popular option for searching and sorting problems.
4. Randomized Algorithms
A randomized algorithm is an algorithm that makes use of random numbers as the basis of its logic. Randomness makes these algorithms less time and space-consuming, and probability is the most significant factor at play. Randomized algorithms are ideal for problems where you have determined that the worst-case scenario is not considerably worse than the best case.
5. Greedy Algorithms
Greedy algorithms work by using the best solution immediately available after each step without worrying how it might affect the next. A greedy algorithm will never reverse an earlier decision, even if the choice was wrong. Greedy algorithms are efficient for solving scheduling and graph theory problems.
6. Backtracking Algorithms
Backtracking algorithms work by moving back and forth until you find a solution to the given problem. The algorithm involves exploring all possible solutions until the end is reached, and then the steps are traced back. Backtracking algorithms are great for traversing trees.
The word algorithm is derived from the name of the 9th-century Persian mathematician Muḥammad ibn Mūsā al-Khwārizmī, whose nisba (identifying him as from Khwarazm) was Latinized as Algoritmi.
Wikipedia
Advantages of an Algorithm
As a programmer, you can decide to go straight into writing code; however, using an algorithm has several advantages:
1. Ease And Efficiency In Coding
A key aspect of writing algorithms is breaking huge problems into smaller bits. If you can master the art (or science) of writing great algorithms, you will find the actual coding easier since you have taken care of the logical side of things.
2. Ease In Communication
Because we write algorithms in typical human languages, you can easily explain them to non-programmers. As a programmer, you might have superiors and team members who do not know how to code; they can understand the step-by-step solution.
3. Makes Debugging Easier
Well-designed algorithms make it easy to debug an error in your program. If you have an algorithm that works well, errors in your program will likely be syntax or runtime errors, and any logical error will likely be a mistake on your part and not an error on the algorithm itself.
4. Can Be Used Across Languages
Since we do not write algorithms in any programming language, programmers can use a good algorithm across various programming languages.
Properties Of An Algorithm
Every well-written algorithm has some standard features:
1. Definiteness
Every instruction in an algorithm should be explicit and without any ambiguity. No statement in an algorithm should be open to multiple interpretations; rather, it should have a definite meaning. Your instructions should also have defined values or variables attached to them.
For example, if you want to run an algorithm that tells the computer to add, you must define what numbers you want to add together.
2. Effectiveness
A good algorithm must fulfill the reason you wrote it, and an algorithm should also not contain unnecessary statements.
Depending on a programmer’s skill, an effect algorithm would eliminate some lines of code that might make the program run longer. However, it is essential not to over condense an algorithm to the point that it becomes too hard to understand (except you’re engaging in competitive programming).
3. Finiteness
Every algorithm should have a finite or countable number of steps. Also, every instruction within the algorithm must take a finite amount of time to complete. No properly-written algorithm should demand the user to terminate it forcefully.
For example, in the case of loops, you must ensure that you set them up toward fulfilling a given condition. If not, your loop would run an infinite number of times. If you have an infinite statement in your program, it cannot function correctly.
4. Input
An algorithm might have multiple inputs or no inputs at all. For example, finding the sum of two numbers would require two inputs, while printing “hello world” to the console would not require any inputs.
4. Output
Every algorithm must have at least an output; the output is the point of the entire algorithm.
Read More: 7 Uses of Python Programming Language