Posts

Showing posts with the label recursion

How To Perform Merge Sort | Sorting Algorithm

Image
In computer science , merge sort is an efficient, general-purpose, comparison-based sorting algorithm .It is a divide and conquer algorithm that was invented by John von Neumann in 1945.   Algorithm        Conceptually, a merge sort works as follows: Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list.  The following diagram shows the complete merge sort process.   Source Code:  Download the code: Merge.c #include<stdio.h> #include<stdlib.h> void mergesort(int a[],int low,int high) {     int mid=(low+high)/2;     if(low<high)     {         mergesort(a,low,mid);         mergesort(a,mid+1,high);  ...

Write a program to print all permutations of a given string

Image
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB. Source Code:  Download the code  : Permutation of string #include <iostream> #include <string.h> using namespace std; int count=0; void swap(char *x, char *y) {     char temp;     temp = *x;     *x = *y;     *y = temp; } void permute(char *a, int l, int r) {    int i;    if (l == r)    {     count++;     cout<<count<<": "<<a<<"\n";    }    else    {        for (i = l; i <= r; i++)        {          ...

N Queen Problem ( Backtracking)

Image
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. For example, following is a solution for 8 Queen problem.   Naive Algorithm:  Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints. Backtracking Algorithm: The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we move to previous column and find other possible position for the previously placed queen. 1) Start in the leftmost column 2) If all queens are placed i.e. fill_count = no of queens Print the board 3) Try all rows in the current column.  Do followin...