Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Sorting Algorithms in C++ by using custom made Header file

In C++, you can create your own header file and declare function prototypes in them. An then you can define the functions in .cpp file.
In this post, I will demonstrate how to implement some the most common sorting algorithms in C++ using a custom made header file.

// sort.h
 
#ifndef SORT_H_
#define SORT_H_
#define n 10 
class sort
{
 private:
  int a[n];
   
 public:
  void display();   
  void input();     
  void bubble_sort();
  void selection_sort();
  void insertion_sort();
  void merge_sort(int[],int,int);
  void quick_sort(int[],int,int);
  void shell_sort();
  void radix_sort();
};
#endif   


// sort.cpp
#include<iostream>
#include "sort.h"
#include<malloc.h>
#include<stdlib.h>
using namespace std;
int b[n];  
void sort::input()
{
 int i;  
 for(i=0;i<n;i++)
  a[i]=rand()%100;
}
void recur_input()
{
 int i;  
 for(i=0;i<n;i++)
  b[i]=rand()%100;
}
void sort::display()
{
 int i;
 for(i=0;i<n;i++)
  cout<<a[i]<<"   ";
}
void recur_display()
{
 int i;
 for(i=0;i<n;i++)
  cout<<b[i]<<"   ";
}
void merge(int a[],int l,int mid,int h)
{ 
 int i=l,j=mid+1,k=l,c[50];
 while((i<=mid)&&(j<=h))
 {
  if(a[i]<=a[j])
   c[k++]=a[i++];
  else
   c[k++]=a[j++];       
 }     
 while(i<=mid)   
  c[k++]=a[i++];    
  
 while(j<=h)
  c[k++]=a[j++];    
 
 for(i=l;i<k;i++) 
  a[i]=c[i];     
}
int partition(int *a,int l,int h)
{
 int i,j,pv;
 pv=a[l];
 i=l,j=h+1;
 do
 {
  while(a[i]<=pv) i++;
  while(a[j]>pv) j--;
  if(i<j) 
  {
   int temp=a[i];
   a[i]=a[j];
   a[j]=temp;
  }
  else break;
 }while(i<=j); 
 int temp=a[l];
 a[l]=a[i-1];
 a[i-1]=temp;   
 return i-1;
} 
void sort::bubble_sort()
{
 int i,j;
 for(i=0;i<n-1;i++)
  for(j=0;j<n-1-i;j++)
   if(a[j]>a[j+1])
   {
    int temp=a[j];
    a[j]=a[j+1];
    a[j+1]=temp;
   }
}
void sort::selection_sort()
{
 int i,j,min,pos;   
 for(i=0;i<n;i++)
 {
  min=a[i];
  pos=i;
  for(j=i+1;j<n;j++)
  {
   if(a[j]<min)
   { 
    min=a[j];    
    pos=j;
   }
  }
  if(pos!=i)
  {
   int temp=a[i];
   a[i]=a[pos];
   a[pos]=temp;
  }
  
 }
}
void sort::insertion_sort()
{
 int temp,i,j;
 for(i=1;i<n;i++)
 {
  temp=a[i];
  for(j=i-1;((j>=0)&&(temp<a[j]));j--)
  {
   a[j+1]=a[j];
  }
  a[j+1]=temp;
 }
}
void sort::merge_sort(int a[],int l,int h)
{ 
 int mid;
 if(l<h)
 { mid=(l+h)/2;
  merge_sort(a,l,mid);
  merge_sort(a,mid+1,h);
  merge(a,l,mid,h);
 }
    
}
void sort::quick_sort(int a[],int l,int h)
{
 int x;
 if(l>=h) return;
 x=partition(a,l,h);
 quick_sort(a,l,x-1);
 quick_sort(a,x+1,h);
}
void sort::shell_sort()
{
 int i,j,d=n*4/5;
 while(d>=1)
 {
  for(i=0;i<n-d;i++)
   if(a[i]>a[i+d]) 
   {
    int temp=a[i];
    a[i]=a[i+d];
    a[i+d]=temp;
   }
  if(d==1)
   break;
  d=d*4/5;
 }
}
void sort::radix_sort()
{
 int i,j,k=1,l,temp,b[10][n],cnt;
 int max=a[0],c=0;
 for(i=0;i<n;i++)
  if(a[i]>max)
   max=a[i];
 while(max%10)
 {
  c++;
  max/=10;
 } 
 for(i=0;i<10;i++)
  for(j=0;j<n;j++)
   b[i][j]=-999; 
 for(l=0;l<c;l++)
 {
  for(j=0;j<n;j++)
  {
   temp=(a[j]/k)%10;
   b[temp][j]=a[j];
  }
  k=k*10; cnt=0;
  for(i=0;i<10;i++)
   for(j=0;j<n;j++)
    if(b[i][j]!=-999)
     a[cnt++]=b[i][j];
  for(i=0;i<10;i++)
   for(j=0;j<n;j++)
    b[i][j]=-999;
 }
}
main()
{
int ch,i;
cout<<"\nProgram of sorting algorithms :\n";
sort s;  
do
{
  cout<<"\n\n[1] Bubble   [2] Selection  [3] Insertion  ";
  cout<<"\n[4] Merge      [5] Quick   [6] Shell Sort ";
  cout<<"\n[7] Radix      [8] Exit ";
  cout<<"\nEnter your choice : ";
  cin>>ch;
  switch(ch)
  {
 case 1: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.bubble_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 2: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.selection_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 3: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.insertion_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 4: 
  recur_input();
  cout<<"\nArray before sorting : \n";
  recur_display();     
  s.merge_sort(b,0,n-1);
  cout<<"\nArray after sorting : \n";
  recur_display();
  break;
 case 5: 
  recur_input();
  cout<<"\nArray before sorting : \n";
  recur_display();    
  s.quick_sort(b,0,n-1);
  cout<<"\nArray after sorting : \n";
  recur_display();
  break;
 case 6: 
  s.input();    
  cout<<"\nArray before sorting : \n";
  s.display();
  s.shell_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 7:
  s.input();     
  cout<<"\nArray before sorting : \n";
  s.display();
  s.radix_sort();
  cout<<"\nArray after sorting : \n";
  s.display();
  break;
 case 8:
  break;
 default: cout<<"\nEnter correct choice .... \n";
  break;     
 }
 }while(ch!=8);  
  
 } 

Merge Sort & External Sort in C

/* merge sort and external sort */
/* EXTMRG.C */
#include 
#include 
#include 

/****************************
 * implementation dependent *
 ****************************/

/* template for workfiles (8.3 format) */
#define FNAME "_sort%03d.dat"
#define LNAME 13

/* comparison operators */
#define compLT(x,y) (x < y)
#define compGT(x,y) (x > y)

/* define the record to be sorted here */
#define LRECL 100
typedef int keyType;
typedef struct recTypeTag {
    keyType key;                                /* sort key for record */
    #if LRECL
        char data[LRECL-sizeof(keyType)];       /* other fields */
    #endif
} recType;

/******************************
 * implementation independent *
 ******************************/

typedef enum {false, true} bool;

typedef struct tmpFileTag {
    FILE *fp;                   /* file pointer */
    char name[LNAME];           /* filename */
    recType rec;                /* last record read */
    int dummy;                  /* number of dummy runs */
    bool eof;                   /* end-of-file flag */
    bool eor;                   /* end-of-run flag */
    bool valid;                 /* true if rec is valid */
    int fib;                    /* ideal fibonacci number */
} tmpFileType;

static tmpFileType **file;      /* array of file info for tmp files */
static int nTmpFiles;           /* number of tmp files */
static char *ifName;            /* input filename */
static char *ofName;            /* output filename */

static int level;               /* level of runs */
static int nNodes;              /* number of nodes for selection tree */

void deleteTmpFiles(void) {
    int i;

    /* delete merge files and free resources */
    if (file) {
        for (i = 0; i < nTmpFiles; i++) {
            if (file[i]) {
                if (file[i]->fp) fclose(file[i]->fp);
                if (*file[i]->name) remove(file[i]->name);
                free (file[i]);
            }
        }
        free (file);
    }
}

void termTmpFiles(int rc) {

    /* cleanup files */
    remove(ofName);
    if (rc == 0) {
        int fileT;

        /* file[T] contains results */
        fileT = nTmpFiles - 1;
        fclose(file[fileT]->fp); file[fileT]->fp = NULL;
        if (rename(file[fileT]->name, ofName)) {
            perror("io1");
            deleteTmpFiles();
            exit(1);
        }
        *file[fileT]->name = 0;
    }
    deleteTmpFiles();
}

void cleanExit(int rc) {

    /* cleanup tmp files and exit */
    termTmpFiles(rc);
    exit(rc);
}

void *safeMalloc(size_t size) {
    void *p;

    /* safely allocate memory and initialize to zero */
    if ((p = calloc(1, size)) == NULL) {
        printf("error: malloc failed, size = %d\n", size);
        cleanExit(1);
    }
    return p;
}

void initTmpFiles(void) {
    int i;
    tmpFileType *fileInfo;

    /* initialize merge files */
    if (nTmpFiles < 3) nTmpFiles = 3;
    file = safeMalloc(nTmpFiles * sizeof(tmpFileType*));
    fileInfo = safeMalloc(nTmpFiles * sizeof(tmpFileType));
    for (i = 0; i < nTmpFiles; i++) {
        file[i] = fileInfo + i;
        sprintf(file[i]->name, FNAME, i);
        if ((file[i]->fp = fopen(file[i]->name, "w+b")) == NULL) {
            perror("io2");
            cleanExit(1);
        }
    }
}

recType *readRec(void) {

    typedef struct iNodeTag {   /* internal node */
        struct iNodeTag *parent;/* parent of internal node */
        struct eNodeTag *loser; /* external loser */
    } iNodeType;

    typedef struct eNodeTag {   /* external node */
        struct iNodeTag *parent;/* parent of external node */
        recType rec;            /* input record */
        int run;                /* run number */
        bool valid;             /* input record is valid */
    } eNodeType;

    typedef struct nodeTag {
        iNodeType i;            /* internal node */
        eNodeType e;            /* external node */
    } nodeType;

    static nodeType *node;      /* array of selection tree nodes */
    static eNodeType *win;      /* new winner */
    static FILE *ifp;           /* input file */
    static bool eof;            /* true if end-of-file, input */
    static int maxRun;          /* maximum run number */
    static int curRun;          /* current run number */
    iNodeType *p;               /* pointer to internal nodes */
    static bool lastKeyValid;   /* true if lastKey is valid */
    static keyType lastKey;     /* last key written */

    /* read next record using replacement selection */

    /* check for first call */
    if (node == NULL) {
        int i;

        if (nNodes < 2) nNodes = 2;
        node = safeMalloc(nNodes * sizeof(nodeType));
        for (i = 0; i < nNodes; i++) {
            node[i].i.loser = &node[i].e;
            node[i].i.parent = &node[i/2].i;
            node[i].e.parent = &node[(nNodes + i)/2].i;
            node[i].e.run = 0;
            node[i].e.valid = false;
        }
        win = &node[0].e;
        lastKeyValid = false;

        if ((ifp = fopen(ifName, "rb")) == NULL) {
            printf("error: file %s, unable to open\n", ifName);
            cleanExit(1);
        }
    }

    while (1) {

        /* replace previous winner with new record */
        if (!eof) {
            if (fread(&win->rec, sizeof(recType), 1, ifp) == 1) {
                if ((!lastKeyValid || compLT(win->rec.key, lastKey))
                && (++win->run > maxRun))
                    maxRun = win->run;
                win->valid = true;
            } else if (feof(ifp)) {
                fclose(ifp);
                eof = true;
                win->valid = false;
                win->run = maxRun + 1;
            } else {
                perror("io4");
                cleanExit(1);
            } 
        } else {
            win->valid = false;
            win->run = maxRun + 1;
        }

        /* adjust loser and winner pointers */
        p = win->parent;
        do {
            bool swap;
            swap = false;
            if (p->loser->run < win->run) {
                swap = true;
            } else if (p->loser->run == win->run) {
                if (p->loser->valid && win->valid) {
                    if (compLT(p->loser->rec.key, win->rec.key))
                        swap = true;
                } else {
                    swap = true;
                }
            }
            if (swap) {
                /* p should be winner */
                eNodeType *t;

                t = p->loser;
                p->loser = win;
                win = t;
            }
            p = p->parent;
        } while (p != &node[0].i);

        /* end of run? */
        if (win->run != curRun) {
            /* win->run = curRun + 1 */
            if (win->run > maxRun) {
                /* end of output */
                free(node);
                return NULL;
            }
            curRun = win->run;
        }

        /* output top of tree */
        if (win->run) {
            lastKey = win->rec.key;
            lastKeyValid = true;
            return &win->rec;
        }
    }
}

void makeRuns(void) {
    recType *win;       /* winner */
    int fileT;          /* last file */
    int fileP;          /* next to last file */
    int j;              /* selects file[j] */


    /* Make initial runs using replacement selection.
     * Runs are written using a Fibonacci distintbution.
     */

    /* initialize file structures */
    fileT = nTmpFiles - 1;
    fileP = fileT - 1;
    for (j = 0; j < fileT; j++) {
        file[j]->fib = 1;
        file[j]->dummy = 1;
    }
    file[fileT]->fib = 0;
    file[fileT]->dummy = 0;

    level = 1;
    j = 0;


    win = readRec();
    while (win) {
        bool anyrun;

        anyrun = false;
        for (j = 0; win && j <= fileP; j++) {
            bool run;

            run = false;
            if (file[j]->valid) {
                if (!compLT(win->key, file[j]->rec.key)) {
                    /* append to an existing run */
                    run = true;
                } else if (file[j]->dummy) {
                    /* start a new run */
                    file[j]->dummy--;
                    run = true;
                }
            } else {
                /* first run in file */
                file[j]->dummy--;
                run = true;
            }

            if (run) {
                anyrun = true;

                /* flush run */
                while(1) {
                    if (fwrite(win, sizeof(recType), 1, file[j]->fp) != 1) {
                        perror("io3");
                        cleanExit(1);
                    }
                    file[j]->rec.key = win->key;
                    file[j]->valid = true;
                    if ((win = readRec()) == NULL) break;
                    if (compLT(win->key, file[j]->rec.key)) break;
                }
            }
        }

        /* if no room for runs, up a level */
        if (!anyrun) {
            int t;
            level++;
            t = file[0]->fib;
            for (j = 0; j <= fileP; j++) {
                file[j]->dummy = t + file[j+1]->fib - file[j]->fib;
                file[j]->fib = t + file[j+1]->fib; 
            }
        }
    }
}

void rewindFile(int j) {
    /* rewind file[j] and read in first record */
    file[j]->eor = false;
    file[j]->eof = false;
    rewind(file[j]->fp);
    if (fread(&file[j]->rec, sizeof(recType), 1, file[j]->fp) != 1) {
        if (feof(file[j]->fp)) {
            file[j]->eor = true;
            file[j]->eof = true;
        } else {
            perror("io5");
            cleanExit(1);
        }
    }
}

void mergeSort(void) {
    int fileT;
    int fileP;
    int j;
    tmpFileType *tfile;

    /* polyphase merge sort */

    fileT = nTmpFiles - 1;
    fileP = fileT - 1;

    /* prime the files */
    for (j = 0; j < fileT; j++) {
        rewindFile(j);
    }

    /* each pass through loop merges one run */
    while (level) {
        while(1) {
            bool allDummies;
            bool anyRuns;

            /* scan for runs */
            allDummies = true;
            anyRuns = false;
            for (j = 0; j <= fileP; j++) {
                if (!file[j]->dummy) {
                    allDummies = false;
                    if (!file[j]->eof) anyRuns = true;
                }
            }

            if (anyRuns) {
                int k;
                keyType lastKey;

                /* merge 1 run file[0]..file[P] --> file[T] */

                while(1) {
                    /* each pass thru loop writes 1 record to file[fileT] */

                    /* find smallest key */
                    k = -1;
                    for (j = 0; j <= fileP; j++) {
                        if (file[j]->eor) continue;
                        if (file[j]->dummy) continue;
                        if (k < 0 || 
                        (k != j && compGT(file[k]->rec.key, file[j]->rec.key)))
                            k = j;
                    }
                    if (k < 0) break;

                    /* write record[k] to file[fileT] */
                    if (fwrite(&file[k]->rec, sizeof(recType), 1, 
                            file[fileT]->fp) != 1) {
                        perror("io6");
                        cleanExit(1);
                    }

                    /* replace record[k] */
                    lastKey = file[k]->rec.key;
                    if (fread(&file[k]->rec, sizeof(recType), 1,
                            file[k]->fp) == 1) {
                        /* check for end of run on file[s] */
                        if (compLT(file[k]->rec.key, lastKey))
                            file[k]->eor = true;
                    } else if (feof(file[k]->fp)) {
                        file[k]->eof = true;
                        file[k]->eor = true;
                    } else {
                        perror("io7");
                        cleanExit(1);
                    }
                }

                /* fixup dummies */
                for (j = 0; j <= fileP; j++) {
                    if (file[j]->dummy) file[j]->dummy--;
                    if (!file[j]->eof) file[j]->eor = false;
                }

            } else if (allDummies) {
                for (j = 0; j <= fileP; j++)
                    file[j]->dummy--;
                file[fileT]->dummy++;
            }

            /* end of run */
            if (file[fileP]->eof && !file[fileP]->dummy) {
                /* completed a fibonocci-level */
                level--;
                if (!level) {
                    /* we're done, file[fileT] contains data */
                    return;
                }

                /* fileP is exhausted, reopen as new */
                fclose(file[fileP]->fp);
                if ((file[fileP]->fp = fopen(file[fileP]->name, "w+b"))
                        == NULL) {
                    perror("io8");
                    cleanExit(1);
                }
                file[fileP]->eof = false;
                file[fileP]->eor = false;

                rewindFile(fileT);

                /* f[0],f[1]...,f[fileT] <-- f[fileT],f[0]...,f[T-1] */
                tfile = file[fileT];
                memmove(file + 1, file, fileT * sizeof(tmpFileType*));
                file[0] = tfile;

                /* start new runs */
                for (j = 0; j <= fileP; j++)
                    if (!file[j]->eof) file[j]->eor = false;
            }
        }

    }
}


void extSort(void) {
    initTmpFiles();
    makeRuns();
    mergeSort();
    termTmpFiles(0);
}

int main(int argc, char *argv[]) {

    /* command-line:
     *
     *   ext ifName ofName nTmpFiles nNodes
     *
     *   ext in.dat out.dat 5 2000
     *       reads in.dat, sorts using 5 files and 2000 nodes, output to out.dat
     */
    if (argc != 5) {
        printf("%s ifName ofName nTmpFiles nNodes\n", argv[0]);
        cleanExit(1);
    }

    ifName = argv[1];
    ofName = argv[2];
    nTmpFiles = atoi(argv[3]);
    nNodes = atoi(argv[4]);

    printf("extSort: nFiles=%d, nNodes=%d, lrecl=%d\n",
        nTmpFiles, nNodes, sizeof(recType));

    extSort();

    return 0;
}

How to implement Bubble Sort using method call and inheritance in Java ?

import java.io.*;
class run
{
        void sort(int a[],int n)
        {
            int i,j;
            for(i=0;i<n-1;i++)
                for(j=0;j<n-1-i;j++)
                    if(a[j] > a[j+1])
                    {
                        int temp = a[j];
                        a[j]=a[j+1];
                        a[j+1]=temp;
                    }
        }
        public void display(int a[],int n)
        {
            for(int i=0;i<n;i++)
                System.out.print(a[i] + "   ");
   
        }
}
public class bubble extends run
{
    public static void main(String args[])throws IOException
    {
        System.out.print("\nProgram to sort array using bubble sort : \n");
        int n,i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("\nEnter array capacity : ");
        n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        for(i=0;i<n;i++)
            a[i]=(int)(Math.random()*100);
        run obj=new run();
        System.out.print("\nArray before sorting : ");
        obj.display(a,n);
        obj.sort(a,n);
        System.out.print("\nArray after sorting : ");
        obj.display(a,n);
    } 
}

Implement Heap Sort in C Programming

#include<stdio.h> 
void  heap_sort(int *, int ); 
void create_heap(int *, int); 
void display(int *, int); 
void create_heap(int list[], int n ) 
{ 
    int k, j, i, temp; 
    for(k = 2 ; k <= n;  ++k) 
    { 
        i = k ; 
        temp = list[k]; 
        j = i / 2 ; 
        while((i > 1) && (temp > list[j])) 
        { 
            list[i] = list[j]; 
            i = j ; 
            j = i / 2 ; 
            if ( j < 1 ) 
                j = 1 ; 
        } 
        list[i] = temp ; 
    } 
} 
void heap_sort(int list[], int n) 
{ 
    int k, temp, value, j, i, p; 
    int step = 1; 
    for(k = n ; k >= 2; --k) 
    { 
        temp = list[1] ; 
        list[1] = list[k]; 
        list[k] = temp ; 
        i = 1 ; 
        value = list[1]; 
        j = 2 ; 
        if((j+1) < k) 
            if(list[j+1] > list[j]) 
                j ++; 
        while((j <= ( k-1)) && (list[j] > value)) 
        { 
            list[i] = list[j]; 
            i = j ; 
            j = 2*i ; 
            if((j+1) < k) 
                if(list[j+1] > list[j]) 
                    j++; 
                else 
                    if( j > n) 
                        j = n ; 
            list[i] = value; 
        }  
        printf("\n Step = %d ", step); 
        step++;    
        for(p = 1; p <= n; p++) 
            printf(" %d", list[p]); 
    } 
} 
void display(int list[], int n) 
{ 
    int i; 
    for(i = 1 ; i <= n; ++ i) 
    { 
        printf("  %d", list[i]); 
    } 
} 
void main() 
{ 
    int list[100]; 
    int i, n ; 
    printf("\n Size of the list:"); 
    scanf(" %d", &n); 
    for(i = 1 ; i <= n ; ++i) 
    { 
        list[i] = rand() % 100; 
    } 
    printf("\n Entered list is as follows:\n"); 
    display(list, n); 
    create_heap(list, n); 
    printf("\n Heap\n"); 
    display(list, n); 
    printf("\n\n"); 
    heap_sort(list,n); 
    printf("\n\n Sorted list is as follows :\n\n"); 
    display(list,n); 
}

Radix Sort in Java

import java.io.*;
public class radix
{
    public void radix(int a[],int n)throws IOException
    {
            int i,j,k=1,l,temp,cnt;
            int b[][]=new int[10][n];
            int max=a[0],c=0;
            for(i=0;i<n;i++)
                if(a[i]>max)
                    max=a[i];
            while(max%10!=0)
                {
                    c++;
                    max/=10;
                }   
            for(i=0;i<10;i++)
                for(j=0;j<n;j++)
                    b[i][j]=-999;   
            for(l=0;l<c;l++)
            {
                for(j=0;j<n;j++)
                    {
                        temp=(a[j]/k)%10;
                        b[temp][j]=a[j];
                    }
                   
                k=k*10;    cnt=0;
                for(i=0;i<10;i++)
                    for(j=0;j<n;j++)
                        if(b[i][j]!=-999)
                            a[cnt++]=b[i][j];
                for(i=0;i<10;i++)
                    for(j=0;j<n;j++)
                        b[i][j]=-999;
            }
    }
    public void main(String args[])throws IOException
    {
        System.out.print("\nProgram to sort array using radix sort sort : \n");
        int n,i;
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("\nEnter array capacity : ");
        n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        for(i=0;i<n;i++)
            a[i]=(int)(Math.random()*100);          
        System.out.print("\nArray before sorting : ");
        for(i=0;i<n;i++)
            System.out.print(a[i] + "   ");
        radix(a,n);
        System.out.print("\nArray after sorting : ");
        for(i=0;i<n;i++)
            System.out.print(a[i] + "   ");

    }
}

Recursive Merge Sort in Java

import java.io.*;
public class merge
{
    void merge(int a[],int l,int mid,int h)
       {   
        int i=l,j=mid+1,k=l;
        int c[]=new int[50];
           
        while((i<=mid)&&(j<=h))
            {
                if(a[i]<=a[j])
                    c[k++]=a[i++];
                else
                    c[k++]=a[j++];        // l=low                  
            }                    // h=high
        while(i<=mid)           
            c[k++]=a[i++];               
           
        while(j<=h)
            c[k++]=a[j++];               
       
        for(i=l;i<k;i++)    // necessary loop
            a[i]=c[i];                   
       }
    void merge_sort(int a[],int l,int h)
       {
        int mid;
        if(l<h)
            {    mid=(l+h)/2;
                merge_sort(a,l,mid);
                merge_sort(a,mid+1,h);
                merge(a,l,mid,h);
            }
     } 
    public void main(String args[])throws IOException
{
    System.out.print("\nProgram to sort array using merge sort : \n");
    int n,i;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("\nEnter array capacity : ");
    n=Integer.parseInt(br.readLine());
    int a[]=new int[n];
    for(i=0;i<n;i++)
        a[i]=(int)(Math.random()*100);          // Generates random numbers
   System.out.print("\nArray before sorting : ");
    for(i=0;i<n;i++)
        System.out.print(a[i] + "   ");
        merge_sort(a,0,n-1);
    System.out.print("\nArray after sorting : ");
    for(i=0;i<n;i++)
        System.out.print(a[i] + "   ");

    }
   
}

Recursive Quick Sort in Java

/* Quick Sort in Java  */ 

import java.io.*;
public class quick
{
  void quicksort(int a[],int l,int h)throws IOException
  {
      int x;
      if(l < h)
      {
        x=partition(a,l,h);
        quicksort(a,l,x-1);
        quicksort(a,x+1,h);
      }
  }
  int partition(int a[],int l,int h)throws IOException
  {
     int i=l,j=h,pv=a[l];
     while(i<=j)
     {       
         while(a[i]<=pv)    i++;    
         while(a[j]>pv)     j--;
         if(i<j)
         {
             int temp=a[i];
              a[i]=a[j];
              a[j]=temp;
         }
    }
    int temp1=a[l];
    a[l]=a[j];
    a[j]=temp1;
    return (i-1);
}
public void main(String args[])throws IOException
{
    System.out.print("\nProgram to sort array using quick sort : \n");
    int n,i;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.print("\nEnter array capacity : ");
    n=Integer.parseInt(br.readLine());
    int a[]=new int[n];
    for(i=0;i<n;i++)
        a[i]=(int)(Math.random()*100);          // Generates random numbers 
   System.out.print("\nArray before sorting : ");
    for(i=0;i<n;i++)
        System.out.print(a[i] + "   ");
        quicksort(a,0,n-1);
    System.out.print("\nArray after sorting : ");
    for(i=0;i<n;i++)
        System.out.print(a[i] + "   ");

    }
}

Bubble Sort in C++


    #include<iostream>
    #include<stdio.h>
    void swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void bubble_sort(int a[],int n)
    {
        int i,j;
        for(i=0;i<n-1;i++)
            for(j=0;j<n-1-i;j++)
                if(a[j]>a[j+1])
                    swap(a,j,j+1);

    }

    main()
        {    int i,n;
            std::cout<<"Program to sort using bubblesort :"<<"\n";
            std::cout<<"Enter array capacity :" ;
            std::cin>>n;
            int a[n];
            std::cout<<"Enter the numbers : "<<"\n";
            for(i=0;i<n;i++)
                std::cin>>a[i];
            printf("\nGIVEN ARRAY :  ");
            for(i=0;i<n;i++)
                std::cout<<a[i]<<"  ";
            printf("\n\nSORTED ARRAY : ");
            bubble_sort(a,n);
            for(i=0;i<n;i++)
                std::cout<<a[i]<<"  ";
            std::cout<<"\n\n";
        }
                   

Bubble Sort in Java

  public class bubble
    {
        public static void bubble(int a[],int n)
        {
            int i,j;
            for(i=0;i<n-1;i++)
                for(j=0;j<n-1-i;j++)
                    if(a[j] > a[j+1])
                    {
                        int temp = a[j];
                        a[j]=a[j+1];
                        a[j+1]=temp;
                    }
        }
        public static void main(String args[])
        {
            System.out.println();
            System.out.println("Program of Bubble Sort :");
            int a[]={34,89,-21,78,12,-6,67,45};
            int i,n=8;
            System.out.print("Given array :");
            for(i=0;i<n;i++)
                System.out.print(a[i] + "  ");
            System.out.println();
            bubble(a,n);
            System.out.print("Sorted array : ");
            for(i=0;i<n;i++)
                System.out.print(a[i] + "  ");
            System.out.println();
        }
    } 

Selection Sort in Java

 public class selsort
    {
        public static void selsort(int a[],int n)
        {
            int i,j,min,pos=0;            
            for(i=0;i<n;i++)
            {
                min=a[i];
                pos=i;
                for(j=i+1;j<n;j++)
                {
                    if(a[j]<min)
                    {    
                        min=a[j];                
                        pos=j;
                    }
                }
                int temp=a[i];
                a[i]=a[pos];
                a[pos]=temp;
            }
        }
        
        public static void main(String args[])
        {
            System.out.println("Program to sort an array using selection sort : ");
            int a[]={23,-34,68,35,-21,99,45,65,81,26};
            int n=10,i;
            System.out.println("\n\nGiven array : ");
            for(i=0;i<n;i++)
                System.out.print(a[i]+ "  ");
            selsort(a,n);
            System.out.println("\n\n");
            System.out.println("Sorted array : ");
            for(i=0;i<n;i++)
                System.out.print(a[i]+ "  ");
            System.out.println();
        }
    }

Shell Sort Programming in C

#include<stdio.h>
    void swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void shellsort(int a[],int n)
        {
            int i,j,d=n*4/5;
            while(d>=1)
            {        for(i=0;i<n-d;i++)
                        if(a[i]>a[i+d])    
                            swap(a,i,i+d);
                if(d==1)    break;
                d=d*4/5;
            }
        }
    main()
        {
            int i,n;
            printf("\nProgram to sort an array using shell sort : \n");
            printf("Enter array capacity : \n");
            scanf("%d",&n);
            int a[n];
            for(i=0;i<n;i++)
                a[i]=rand()%100;
            printf("Initial array : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            shellsort(a,n);
            printf("\nSorted array  : ");
            for(i=0;i<n;i++)
                 printf("%4d",a[i]);
            printf("\n");
        }

Selection Sort using minimum number in C

/* Selection sort using minimum  */

    #include<stdio.h>
    int swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void selsort(int a[],int n)
        {
            int i,j,min,pos;            
            for(i=0;i<n;i++)
            {
                min=a[i];
                for(j=i+1;j<n;j++)
                {
                    if(a[j]<min)
                    {    
                        min=a[j];                
                        pos=j;
                    }
                }
                swap(a,i,pos);
            }
            printf("SORTED ARRAY : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            printf("\n");
        }

    main()
        {    
            int i,n;
            printf("Enter array capacity : \n");
            scanf("%d",&n);
            int a[n];
            for(i=0;i<n;i++)
                *(a+i)=rand()%100;
            printf("INITIAL ARRAY  : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            printf("\n");
            selsort(a,n);
        }

Selection Sort using maximum number in C

/* Selection sort using maximum  */

    #include<stdio.h>
    int swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void selsort(int a[],int n)
        {
            int i,j,max,pos;            
            for(i=n-1;i>=0;i--)
            {
                max=a[i];
                pos=i;        
                for(j=i-1;j>=0;j--)
                {
                    if(a[j]>max)
                    {    
                        max=a[j];                
                        pos=j;
                    }
                }
                swap(a,i,pos);
            }
            printf("SORTED ARRAY : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            printf("\n");
        }

    main()
        {    
            int i,n;
            printf("Enter array capacity : \n");
            scanf("%d",&n);
            int a[n];
            for(i=0;i<n;i++)
                *(a+i)=rand()%100;
            printf("INITIAL ARRAY  : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            printf("\n");
            selsort(a,n);
        }

Radix Sort in C programming

#include<stdio.h>
    void radix(int a[],int n)
        {
            int i,j,k=1,l,temp,b[10][n],cnt;
            int max=a[0],c=0;
            for(i=0;i<n;i++)
                if(a[i]>max)
                    max=a[i];
            while(max%10)
                {
                    c++;
                    max/=10;
                }    
            for(i=0;i<10;i++)
                for(j=0;j<n;j++)
                    b[i][j]=-999;    
            for(l=0;l<c;l++)
            {
                for(j=0;j<n;j++)
                    {
                        temp=(a[j]/k)%10;
                        b[temp][j]=a[j];
                    }
                    
                k=k*10;    cnt=0;
                for(i=0;i<10;i++)
                    for(j=0;j<n;j++)
                        if(b[i][j]!=-999)
                            a[cnt++]=b[i][j];
                for(i=0;i<10;i++)
                    for(j=0;j<n;j++)
                        b[i][j]=-999;
            }
        }
    main()
        {
            int i,n;
            printf("Enter array capacity \t: ");
            scanf("%d",&n);
            int a[n];
            for(i=0;i<n;i++)
                a[i]=rand()%100;
            printf("\nArray Before Sorting : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);            
            radix(a,n);
            printf("\n\nArray After Sorting : ");
            for(i=0;i<n;i++)
            printf("%4d",a[i]);
            printf("\n");

        }

Recursive Quick sort in C programming

 /*  Recursive Quick Sort in C  */

    #include<stdio.h>
    int n;
    void swap(int *a,int x,int y)
    {
        int temp=*(a+x);
        *(a+x)=*(a+y);
        *(a+y)=temp;
    }
    void quicksort(int *a,int l,int h)
    {
        int x;
        if(l>=h)
        return;
        x=partition(a,l,h);
        quicksort(a,l,x-1);
        quicksort(a,x+1,h);
    }
    int partition(int *a,int l,int h)
    {
        int i,j,pv;
        pv=a[l];
        i=l,j=h;
        while(i<=j)
        {        
                   while(a[i]<=pv)
                          i++;
                while(a[j]>pv)
                          j--;
                if(i<j)
                          swap(a,i,j);
    }
    swap(a,l,j);
    int k=0;
    printf("\n");
    for(k=0;k<n;k++)
        printf("%4d",a[k]);
    printf("\n");
    return(i-1);
}            
main()
{
    int i,j;
    printf("\nProgram to sort data using quick sort:-\n\n");
    printf("Enter number of elements:");
    scanf("%d",&n);
    int a[n];
    srand(time(NULL));
    for(i=0;i<n;i++)
        a[i]=rand()%100;
    printf("\nBefore Sorting:-\n\n");
    for(i=0;i<n;i++)
        printf("%4d",a[i]);
    
    quicksort(a,0,n-1);
    
    printf("\n\nAfter Sorting:-\n\n");
    for(i=0;i<n;i++)
        printf("%4d",a[i]);
        printf("\n");    
}


Recursive Merge Sort

/*  Recursive Merge Sort in C Programming */
 #include<stdio.h>
 merge(int a[],int l,int mid,int h)
       {    
        int i=l,j=mid+1,k=l,c[50];
            
        while((i<=mid)&&(j<=h))
            {
                if(a[i]<=a[j])
                    c[k++]=a[i++];
                else
                    c[k++]=a[j++];        // l=low                   
            }                    // h=high
        while(i<=mid)            
            c[k++]=a[i++];                
            
        while(j<=h)
            c[k++]=a[j++];                
        
        for(i=l;i<k;i++)    // necessary loop
            a[i]=c[i];                    
       }
    merge_sort(int a[],int l,int h)
       {
        int mid;
        if(l<h)
            {    mid=(l+h)/2;
                merge_sort(a,l,mid);
                merge_sort(a,mid+1,h);
                merge(a,l,mid,h);
            }
     }         
    

        main()
            {
                int i,n;
                printf("\nProgram to sort an array using merge sort : \n");
                printf("Enter array capacity : \n");
                scanf("%d",&n);
                int a[n];
                for(i=0;i<n;i++)
                    a[i]=rand()%100;
                
                printf("Initial array :   ");
                for(i=0;i<n;i++)
                    printf("%4d",a[i]);
                    printf("\n");
                
                merge_sort(a,0,n-1);    //   merge function

                printf("\nSorted array : ");
                for(i=0;i<n;i++)
                    printf("%4d",a[i]);
                printf("\n");            
            }

Non- Recursive merge sort

    #include<stdio.h>
    int swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void merge(int a[],int n)
    {
        int c[n],k=0;
        int i,j;           
        for(i=0;i<n/2;i++)
            for(j=0;j<n/2-1;j++)
                if(a[j]>a[j+1])
                    swap(a,j,j+1);
        printf("\nBubble output 1 : ");
        for(i=0;i<n/2;i++)
            printf("%4d",a[i]);
       
        for(i=n/2;i<n;i++)
            for(j=n/2;j<n-1;j++)
                if(a[j]>a[j+1])
                    swap(a,j,j+1);       
                   
        printf("\nBubble output 2 : ");
        for(i=n/2;i<n;i++)
            printf("%4d",a[i]);
        printf("\n");

   

        int p=0,q=n/2;
        while((p<=n/2)&&(q<=n-1))
            {
                if(a[p]<=a[q])
                    c[k++]=a[p++];
                else
                    c[k++]=a[q++];
                   
            }
        while(p<=n/2)
            c[k++]=a[p++];
               
           
        while(q<=n-1)
            c[k++]=a[q++];
               
       
        printf("Sorted array :  ");
        for(i=0;i<n;i++)
            printf("%4d",c[i]);
        printf("\n");
       
    }


        main()
            {
                int i,n;
                //int a[]={45,23,12,56,76,54,34,33,21,22};
                printf("\n\nEnter array capacity : \n");
                scanf("%d",&n);
                int a[n];
                for(i=0;i<n;i++)
                    *(a+i)=rand()%100;
               
                printf("Initial array :   ");
                for(i=0;i<n;i++)
                    printf("%4d",a[i]);
                    printf("\n");

                merge(a,n);
            }

Insertion Sort

      /* Insertion sort */

    #include<stdio.h>
    int swap(int *a,int x,int y)
        {
            int temp=*(a+x);
            *(a+x)=*(a+y);
            *(a+y)=temp;
        }
    void insertion_sort(int a[],int n)
        {
            int temp,i,j;
            for(i=1;i<n;i++)
            {
                temp=a[i];
                for(j=i-1;((j>=0)&&(temp<a[j]));j--)
                {
                    a[j+1]=a[j];
                }
                a[j+1]=temp;
                
            }

            printf("SORTED ARRAY : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            printf("\n");
        }

        main()
        {    
            int i,n;
            printf("Enter array capacity : \n");
            scanf("%d",&n);
            int a[n];
            for(i=0;i<n;i++)
                *(a+i)=rand()%100;
            printf("INITIAL ARRAY  : ");
            for(i=0;i<n;i++)
                printf("%4d",a[i]);
            printf("\n");
            insertion_sort(a,n);
        }

Top