Search

26 October, 2017

C Program to Find LCM and HCF of Two Numbers




25 October, 2017

Classification of algorithms

There are broadly 4 ways in which classification of algorithms can be done.
1.  Classification by purpose
Each algorithm has a goal, for example, the purpose of the Quick Sort algorithm is to sort data in ascending or descending order. But the number of goals is infinite, and we have to group them by kind of purposes.
2.  Classification by implementation
  • Recursive or iterative
    A recursive algorithm is one that calls itself repeatedly until a certain condition matches. It is a method common to functional programming. 
    For example, the towers of hanoi problem is well understood in recursive implementation. Every recursive version has an iterative equivalent iterative, and vice versa.
  • Logical or procedural
    An algorithm may be viewed as controlled logical deduction. 
    A logic component expresses the axioms which may be used in the computation and a control component determines the way in which deduction is applied to the axioms.
  • Serial or parallel                                                                                Algorithms are usually discussed with the assumption that computers execute one instruction of an algorithm at a time. This is a serial algorithm, as opposed to parallel algorithms, which take advantage of computer architectures to process several instructions at once. Sorting algorithmscan be parallelized efficiently.
  • Deterministic or non-deterministic
    Deterministic algorithms solve the problem with a predefined process whereas non-deterministic algorithm must perform guesses of best solution at each step through the use of heuristics.

3.   Classification by design paradigm
  • Divide and conquer
    A divide and conquer algorithm repeatedly reduces an instance of a problem to one or more smaller instances of the same problem (usually recursively), until the instances are small enough to solve easily. One such example of divide and conquer is merge sorting. The binary search algorithm is an example of a variant of divide and conquer called decrease and conquer algorithm, that solves an identical subproblem and uses the solution of this subproblem to solve the bigger problem. 
  • Dynamic programming
    The shortest path in a weighted graph can be found by using the shortest path to the goal from all adjacent vertices. 
    When the optimal solution to a problem can be constructed from optimal solutions to subproblems, using dynamic programming avoids recomputing solutions that have already been computed. 
    - The main difference with the "divide and conquer" approach is, subproblems are independent in divide and conquer, where as the overlap of subproblems occur in dynamic programming. 
    - Dynamic programming and memoization go together. The difference with straightforward recursion is in caching or memoization of recursive calls. Where subproblems are independent, this is useless. By using memoization or maintaining a table of subproblems already solved, dynamic programming reduces the exponential nature of many problems to polynomial complexity.
  • The greedy method
    A greedy algorithm is similar to a dynamic programming algorithm, but the difference is that solutions to the subproblems do not have to be known at each stage. Instead a "greedy" choice can be made of what looks the best solution for the moment. 
    The most popular greedy algorithm is finding the minimal spanning tree as given by Kruskal.
  • Linear programming
    The problem is expressed as a set of linear inequalities and then an attempt is made to maximize or minimize the inputs. This can solve many problems such as the maximum flow for directed graphs, notably by using the simplex algorithm. 
    A complex variant of linear programming is called integer programming, where the solution space is restricted to all integers.
  • Reduction also called transform and conquer
    Solve a problem by transforming it into another problem. A simple example:finding the median in an unsorted list is first translating this problem into sorting problem and finding the middle element in sorted list. The main goal of reduction is finding the simplest transformation possible.
  • Using graphs
    Many problems, such as playing chess, can be modeled as problems on graphs. A graph exploration algorithms are used. 
    This category also includes the search algorithms and backtracking.
4.  The probabilistic and heuristic paradigm 
  1. Probabilistic 
    Those that make some choices randomly.
  2. Genetic 
    Attempt to find solutions to problems by mimicking biological evolutionary processes, with a cycle of random mutations yielding successive generations of "solutions". Thus, they emulate reproduction and "survival of the fittest".
  3. Heuristic 
    Whose general purpose is not to find an optimal solution, but an approximate solution where the time or resources to find a perfect solution are not practical.
1. Searching and sorting algorithms -
Sorting algorithms include Quicksort , Merge sort, Heapsort, Bubble sort,Insertion sort, Radix sort. Other imp soting algorithms are Topological sort, Counting sort, Shell sort A comprehensive list can be found here.

Important searching algorithms include breadthdepth first  search, binary search etc.

2. Dynamic Programming -- To name a few DP problems, Longest Common Subsequence problemKnapsacktravelling salesman problemetc.

3. Graph algorithms -- Important graph algorithms are DijkstraPrim,KruskalBellman-Ford. A comprehensive list can be found

Program in C

http://cbasicprogram.blogspot.in

20 October, 2017

What is an algorithm?

What is an algorithm?

Informally, an algorithm is any well-defined computational procedure that takes
some value, or set of values, as input and produces some value, or set of values, as
output. An algorithm is thus a sequence of computational steps that transform the
input into the output
Source: Thomas H. Cormen, Chales E. Leiserson (2009), Introduction to Algorithms 3rd edition.
In simple terms, it is possible to say that an algorithm is a sequence of steps which allow to solve a certain task ( Yes, not just computers use algorithms, humans also use them). Now, an algorithm should have three important characteristics to be considered valid:
  1. It should be finite: If your algorithm never ends trying to solve the problem it was designed to solve then it is useless
  2. It should have well defined instructions: Each step of the algorithm has to be precisely defined; the instructions should be unambiguously specified for each case.
  3. It should be effective: The algorithm should solve the problem it was designed to solve. And it should be possible to demonstrate that the algorithm converges with just a paper and pencil.


Basic Sql statements

INSERT        
   INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger', 'Norway');

UPDATE      
 UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

DELETE     
 DELETE FROM Customers
WHERE CustomerName='Alfreds Futterkiste';


SELECT WHERE
 SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin'SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
SELECT * FROM Customers
WHERE NOCountry='Germany';
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');

SELECT TOP
SELECT TOP 3 * FROM Customers; SELECT * FROM Customers
LIMIT 3;
SELECT * FROM Customers
WHERE ROWNUM <= 3;
SELECT TOP 50 PERCENT * FROM Customers; SELECT * FROM Customers
WHERE Country='Germany' AND ROWNUM <= 3;


ORDER BY  
 SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;


Aggregate function


SELECT MIN(Price) AS SmallestPrice
FROM Products;
SELECT COUNT(ProductID) FROM Products;
SELECT SUM(Quantity) FROM OrderDetails;


LIKE              
 SELECT * FROM Customers
WHERE CustomerName LIKE 'a%'; // a at the start
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%'; //or in any position
SELECT * FROM Customers
WHERE CustomerName LIKE 'a_%_%' //SQL statement selects all customers with a
CustomerName that starts with "a" and are at least 3 characters in length:
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%'; //

IN                   
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
SELECT * FROM Customers

WHERE Country IN (SELECT Country FROM Suppliers);


BETWEEN
     SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20) AND NOT CategoryID IN (1,2,3);
JOIN              
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

INNER JOIN


SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

LEFT JOIN   
 SELECT Customers.CustomerName, Orders.OrderID FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Customers.CustomerName;

RIGHT JOIN
 SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;


FULL OUTER JOIN
SELECT Customers.CustomerName, Orders.OrderID FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;

SELF JOIN     
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2,A.City FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID AND A.City = B.City
ORDER BY A.City; // join with itself

UNION          
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

GROUP BY


SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

HAVING 
  SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID) GROUP BY LastName HAVING COUNT(Orders.OrderID) > 10;


DDL:

PK/FK               
   CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

CHECK             
    CREATE TABLE Persons ( ID int NOT NULL,
LastName varchar(255) NOT NULL, FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
INDEX         
        CREATE INDEX idx_lastname
ON Persons (LastName);


AUTO INCREAMENT

CREATE TABLE Persons (
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL, FirstName varchar(255),
Age int,
PRIMARY KEY (ID)


);

VIEW                  
  CREATE VIEW [Current Product List] AS SELECT ProductID, ProductName
FROM Products

WHERE Discontinued = No;