Hope everyone gained some fundamental view of Data structure and algorithm. Let’s see about algorithms.

**Definition**

“Algorithm is a very well defined and finite number of computational procedures that takes certain value or set of values as input and produces certain value as corresponding output.”

**Characteristics of an Algorithm**

- Must have minimal number of procedures for a specified task in order to be
*efficient*. - Should terminate at some point
- Must be finite

For example assume that we have to sort a given sequence of numbers in ascending order. This is a common problem can be found in many standard design techniques and analysis tools. So here

**Input – **a sequence of numbers **< a _{1}, a_{2}, a_{3}… a_{n}>**

**Output – **a reordered sequence of given set **< b _{1}, b_{2}, b_{3}… b_{n}>**

For example given sequence of numbers are <21, 6, 14, 3, 7, 10, 5>, a sorting algorithm returns as output <3, 5, 6, 7, 10, 14, 21>, such an input is called an ** instance** if the algorithm. In general an instance of a problem is consist of the input needed to compute a solution to the problem.

**Which algorithm is best for a given application…?**

- The number of process to be done
- The extent which the problem has already solved
- Possible restrictions on the input, output and procedures
- Architecture of the computer
- Kind of storage devices to be used

**Practical – 01**

Insertion algorithm is one of the most popular algorithms used to sort given set of number. Let’s have a brief look on this algorithm.

**1.** Assume the first element is already sorted

**2.** Pick the next element from the unsorted portion of the set and compare it with the first element. If it is less than the first element then swap them. Else move to next step.

**3.** Again pick the third element (value) from the set and compare it with second if it is less than second element assign that element in third element’s index. Now again check that number with the first element if it is less than first element then place the first element value in second element’s index. Likewise repeat the task until there is that less than condition is being false and place that value in the false occurring index

5. Process continues until the list is sorted

**Task: Write a java program to sort a given set of Numbers using the Insertion Sort**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class InsertionSort { public static void main (String [] args) { int loc = 0;//place to store new value int value = 0;// value to be stored int [] num = {5,2,11,6,0,15,14,19}; for (int k = 1; k < num.length; k++) { loc = k; value = num[k]; while (loc > 0 && num[loc-1] > value) { num[loc] = num[loc-1]; loc = loc -1; } num[loc] = value; } for (int i = 0; i < num.length; i++) { System.out.print(num[i]+", "); } } } |

**Mathanraj Sharma**

University of Jaffna