Posts

Showing posts from June, 2017

Selection sort | Sorting algorithm

Image
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.  The algorithm maintains two subarrays in a given array.   1) The subarray which is already sorted.  2) Remaining subarray which is unsorted.   In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.                  Source code:   Download the code here: Selection_sort.cpp #include<iostream> using namespace std; //function for performing selection sort void selection_sort(int a[],int n) {     int i,j,k,temp,min_indx;           for(i=0;i<n-1;i++)     {         min_indx=i;                  for(j=i+1;j<n;j++)         {             if(a[j]<a[min_indx])             {                 min_indx=j;             }         }          // swap          temp=a[min_indx];

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++)        {           swap((a+l), (a+i));           permute(a, l+1, r);           swap((a+l), (a+i));        }    } } int main() {     char str[100];     int n;     cin>>str;     cout<<"\nPermutations of the given string :\n";     n = strlen(s