Saturday, January 19, 2019

Link to my new blog

Monday, January 18, 2016

JSP custom tags study link

http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPTags5.html

Friday, January 15, 2016

Jump Start with Activiti BPM along with Spring mvc

To create web application using spring mvc and activiti in background

This post has been migrated to following link.

 My new blog

steps :1
create maven project with following pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>

 <groupId>com.gk</groupId>

 <artifactId>activitiMakerChecker</artifactId>

 <packaging>war</packaging>

 <version>0.0.1-SNAPSHOT</version>

 <name>activitiMakerChecker Maven Webapp</name>

 <url>http://maven.apache.org</url>

 <properties>

 <org.springframework.version>4.2.4.RELEASE</org.springframework.version>

  <jdk.version>1.6</jdk.version>

  <spring.version>4.0.5.RELEASE</spring.version>

  <jstl.version>1.2</jstl.version>

  <servletapi.version>3.1.0</servletapi.version>

  <org.hibernate.version>4.0.1.Final</org.hibernate.version>

  <org.hibernate.annotation.version>3.5.6-Final</org.hibernate.annotation.version>

 </properties>

 <dependencies>

  <!-- Activiti dependencies -->

  <dependency>

   <groupId>org.activiti</groupId>

   <artifactId>activiti-engine</artifactId>

   <version>5.14</version>

  </dependency>

  <dependency>

   <groupId>org.activiti</groupId>

   <artifactId>activiti-spring</artifactId>

   <version>5.14</version>

  </dependency>

    <dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-beans</artifactId>

   <version>${org.springframework.version}</version>

  </dependency>

  <dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-context</artifactId>

   <version>4.2.4.RELEASE</version>

  </dependency>

  <dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-jdbc</artifactId>

   <version>4.2.4.RELEASE</version>

  </dependency>

  <dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-tx</artifactId>

   <version>4.2.4.RELEASE</version>

  </dependency>

  <dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-orm</artifactId>

   <version>${org.springframework.version}</version>

  </dependency>

  <dependency>

   <groupId>org.slf4j</groupId>

   <artifactId>slf4j-api</artifactId>

   <version>1.7.2</version>

  </dependency>

  

  

  <!-- Hibernate dep -->

  <dependency>

   <groupId>org.hibernate</groupId>

   <artifactId>hibernate-core</artifactId>

   <version>${org.hibernate.version}</version>

  </dependency>

  <dependency>

   <groupId>org.hibernate</groupId>

   <artifactId>hibernate-entitymanager</artifactId>

   <version>${org.hibernate.version}</version>

  </dependency>

  <dependency>

   <groupId>org.hibernate</groupId>

   <artifactId>hibernate-annotations</artifactId>

   <version>${org.hibernate.annotation.version}</version>

  </dependency>

  <!-- Oracle dependency -->

  <dependency>

   <groupId>com.oracle</groupId>

   <artifactId>ojdbc6</artifactId>

   <version>11.2.0.3</version>

  </dependency>



  <dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-webmvc</artifactId>

   <version>${spring.version}</version>

  </dependency>



  <dependency>

   <groupId>javax.servlet</groupId>

   <artifactId>jstl</artifactId>

   <version>${jstl.version}</version>

  </dependency>





  <dependency>

   <groupId>junit</groupId>

   <artifactId>junit</artifactId>

   <version>3.8.1</version>

   <scope>test</scope>

  </dependency>

 </dependencies>

 <build>

  <finalName>activitiMakerChecker</finalName>

 </build>

</project>







Now run command :



mvn eclipse:eclipse -Dwtpversion=2.0

,
step 2:
web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
    <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


hello-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.0.xsd 
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com" />
<mvc:annotation-driven />

<bean id="dataSource"
class="oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="your url" />
<property name="user" value="user" />
<property name="password" value="password" />

</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>


<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">

<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseSchemaUpdate" value="false" />
<property name="jobExecutorActivate" value="false" />

</bean>

<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
<property name="processEngineConfiguration" ref="processEngineConfiguration" />
</bean>
<bean id="repositoryService" factory-bean="processEngine"
factory-method="getRepositoryService" />
<bean id="runtimeService" factory-bean="processEngine"
factory-method="getRuntimeService" />
<bean id="taskService" factory-bean="processEngine"
factory-method="getTaskService" />
<bean id="historyService" factory-bean="processEngine"
factory-method="getHistoryService" />
<bean id="managementService" factory-bean="processEngine"
factory-method="getManagementService" />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>






step 3


Java code



package com.nuc.process;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.ProcessEngines;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class MyProcess {

 @Autowired
 ProcessEngine processEngine;
 @RequestMapping(value="hello")
 public String sayHello() {
  System.out.println("Controlle is here");
  if(processEngine==null)
  {
   System.out.println("Nulla");
  }
  else
  {
   System.out.println("Not null");
  }
  
  
  return "welcome";
 }
}

Controller class
package com.gk.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.gk.dao.Dao;
import com.gk.dao.User;
import com.nuc.service.UserTaskList;


@Controller
public class MyController {

 @Autowired
 @Qualifier("dao")
 Dao dao;
 
 @Autowired
 private ProcessEngine processEngine;
 @RequestMapping(value=("login"),method=RequestMethod.POST)
 public String login(@RequestParam("name")String name,@RequestParam("pass")String pass,@RequestParam("gName")String gName,HttpSession session
   ) {
  
  User u1=new User();
  u1.setName(name);
  u1.setgName(gName);
  u1.setPass(pass);
//  dao.save(u1);
 // return "welcome";
 
  String vl="rtl";
  String js="/resources/js/rtl.js";
  if(vl.equalsIgnoreCase("rtl"))
  {
    js="/resources/js/rtl.js";
  }
  session.setAttribute("js", js);

 
 //  " rel="stylesheet">
  //    

  User u2=dao.findById(name);
  if(u2!=null)
  {
   if(u1.getPass().equals(u2.getPass())&&u1.getgName().equals(u2.getgName()))
   {
    
    session.setAttribute("user", u1);
    return "welcome";
   }
   else
   {
    return "error";
   }
  }
  else
  {
   return "error";
  }
  
  
 }
 
 @RequestMapping(value="startProcess",method=RequestMethod.GET)
 public String startProcess(HttpSession session) {
  
  System.out.println("starting new process");
  
  Mapvariables=new HashMap();
  variables.put("name", "true");
  processEngine.getRepositoryService().createDeployment().addClasspathResource("myProcess.bpmn20.xml").deploy();
  processEngine.getRuntimeService().startProcessInstanceByKey("myProcess",variables);
  User user=(User)session.getAttribute("user");

  //processEngine.getRuntimeService().setVariablesLocal("vars", variables);
 // processEngine.getRuntimeService().setVariables("var", variables);
  session.setAttribute("processEngine", processEngine);
  return "myTask";
  
 }
 @RequestMapping(value="myTasks",method=RequestMethod.GET)
 public String myTasks(HttpSession session) {
 
 //System.out.println("starting new process");
  
  User user=(User)session.getAttribute("user");
  session.setAttribute("processEngine", processEngine);
  
  return "myTask";
  
 }
 
 @RequestMapping(value="claim",method=RequestMethod.GET)
 public String claim(@RequestParam("id")String id,HttpSession session) {
  
  User user=(User)session.getAttribute("user");
  processEngine.getTaskService().claim(id,user.getName());
  
  return "myTask";
 }
 
 @RequestMapping(value="complete",method=RequestMethod.GET)
 public String complete(@RequestParam("id")String id,HttpSession session) {
  
  User user=(User)session.getAttribute("user");
  processEngine.getTaskService().complete(id);
  
  return "myTask";
 }

}


JSPs


index.jsp


<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    
<body>
<h2>Hello World! gk1</h2>
<center>
<br>
<form method="post" action="login">

<input type="text" name="name">
<br><br>
<input type="password" name="pass">
<br><br>
<select name="gName">
 <option>m</option>
 <option>c</option>
</select>
<br><br><br>
<input type="submit">
</form>
</center>
</body>
</html>

welcome.jsp



<%@page import="com.gk.dao.User"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<%

String myvar=(String)session.getAttribute("js");
%>

 <link href="<c:url value="/resources/css/rtl.css" />" rel="stylesheet">
 <script src=<c:url value="<%=myvar %>" />></script>
</head>
<body>
Welcome <%
User user=(User)session.getAttribute("user");
if(user!=null)
{
 out.print(user.getName());
}

%>

<%= session.getAttribute("js") %>
<c:catch>


</c:catch>
<a href="startProcess">Start Process</a>
<a href="myTasks">MyTasks</a>
</body>
</html>



mytask.jsp



<%@page import="org.activiti.engine.ProcessEngine"%>
<%@page import="org.activiti.engine.task.Task"%>
<%@page import="java.util.List"%>
<%@page import="com.gk.dao.User"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

your tasks


<%
 User user=(User)session.getAttribute("user");
 ProcessEngine processEngine=(ProcessEngine)session.getAttribute("processEngine");
 List<Task>tasks=processEngine.getTaskService().createTaskQuery().taskCandidateGroup(user.getgName()).list();
 out.print("<br>");
 out.print("Tasks in your group");
 for(Task t:tasks)
 {
  out.print("<br>Id:"+t.getId()+"Name:"+t.getName()+"<a href='claim?id="+t.getId()+"'>Claim it</a>");
 }
 out.print("<br>");
 out.print("Your tasks");
 List<Task>myTasks=processEngine.getTaskService().createTaskQuery().taskAssignee(user.getName()).list();
 for(Task t:myTasks)
 {
  out.print("<br>Id:"+t.getId()+"Name:"+t.getName()+"<a href='complete?id="+t.getId()+"'>Complete it</a>");
 }
 
%>
</body>
</html>



Saturday, October 31, 2015

Strings in java are called by value not reference

Why?

Because String is immutable.

Assert in java

public class Test2 
{
    public static int x;
    public static int foo(int y) 
    {
        return y * 2;
    }
    public static void main(String [] args) 
    {
        int z = 5;
        assert z > 0; /* Line 11 */
        assert z > 2: foo(z); /* Line 12 */
        if ( z < 7 )
            assert z > 4; /* Line 14 */

        switch (z) 
        {
            case 4: System.out.println("4 ");
            case 5: System.out.println("5 ");
            default: assert z < 10;
        }

        if ( z < 10 )
            assert z > 4: z++; /* Line 22 */
        System.out.println(z);
    }
}
which line is an example of an inappropriate use of assertions?
A.
Line 11
B.
Line 12
C.
Line 14
D.
Line 22
Answer: Option D
Explanation:
Assert statements should not cause side effects. Line 22 changes the value of z if the assert statement is false.
Option A is fine; a second expression in an assert statement is not required.
Option B is fine because it is perfectly acceptable to call a method with the second expression of an assert statement.
Option C is fine because it is proper to call an assert statement conditionally.

Output of program

public class Test 
{
    public static int y;
    public static void foo(int x) 
    {
        System.out.print("foo ");
        y = x;
    }
    public static int bar(int z) 
    {
        System.out.print("bar ");
        return y = z;
    }
    public static void main(String [] args ) 
    {
        int t = 0;
        assert t > 0 : bar(7);
        assert t > 1 : foo(8); /* Line 18 */
        System.out.println("done ");
    }
}
A.
bar
B.
bar done
C.
foo done
D.
Compilation fails
Answer: Option D
Explanation:
The foo() method returns void. It is a perfectly acceptable method, but because it returns void it cannot be used in an assert statement, so line 18 will not compile.
Learn more problems on : Assertions

Friday, October 30, 2015

Assert in java

Thread And Runnable both have run method which one will be called?

class MyThread extends Thread 
{ 
    MyThread() {} 
    MyThread(Runnable r) {super(r); } 
    public void run() 
    { 
        System.out.print("Inside Thread ");
    } 
} 
class MyRunnable implements Runnable 
{ 
    public void run() 
    { 
        System.out.print(" Inside Runnable"); 
    } 
} 
class Test 
{  
    public static void main(String[] args) 
    { 
        new MyThread().start(); 
        new MyThread(new MyRunnable()).start(); 
    } 
}
A.
Prints "Inside Thread Inside Thread"
B.
Prints "Inside Thread Inside Runnable"
C.
Does not compile
D.
Throws exception at runtime
Answer: Option A
Explanation:
If a Runnable object is passed to the Thread constructor, then the run method of theThread class will invoke the run method of the Runnable object.
In this case, however, the run method in the Thread class is overridden by the run method in MyThread class. Therefore the run() method in MyRunnable is never invoked.
Both times, the run() method in MyThread is invoked instead.


Reference: http://www.indiabix.com/online-test/java-programming-test/61

IllegalThreadStateException

class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread();
        t.start();
        System.out.print("one. ");
        t.start();
        System.out.print("two. ");
    }
    public void run() 
    {
        System.out.print("Thread ");
    }
}
A.
Compilation fails
B.
An exception occurs at runtime.
C.
It prints "Thread one. Thread two."
D.
The output cannot be determined.
Answer: Option B

Explanation:
When the start() method is attempted a second time on a single Thread object, the method will throw an IllegalThreadStateException (you will not need to know this exception name for the exam). Even if the thread has finished running, it is still illegal to call start() again.

short circuit operator in java

class BoolArray 
{
    boolean [] b = new boolean[3];
    int count = 0;

    void set(boolean [] x, int i) 
    {
        x[i] = true;
        ++count;
    }

    public static void main(String [] args) 
    {
        BoolArray ba = new BoolArray();
        ba.set(ba.b, 0);
        ba.set(ba.b, 2);
        ba.test();
    }

    void test() 
    {
        if ( b[0] && b[1] | b[2] )
            count++;
        if ( b[1] && b[(++count - 2)] )
            count += 7;
        System.out.println("count = " + count);
    }
}


Result count = 3

Why?

The reference variables b and x both refer to the same boolean array. count is incremented for each call to the set() method, and once again when the first if test istrue. Because of the && short circuit operator, count is not incremented during the second if test.

Output of program

class SC2 
{
    public static void main(String [] args) 
    {
        SC2 s = new SC2();
        s.start();
    }

    void start() 
    {
        int a = 3;
        int b = 4;
        System.out.print(" " + 7 + 2 + " ");
        System.out.print(a + b);
        System.out.print(" " + a + b + " ");
        System.out.print(foo() + a + b + " ");
        System.out.println(a + b + foo());
    }

    String foo() 
    {
        return "foo";
    }
}


Result
72 7 34 foo34 7foo

Description:

Because all of these expressions use the + operator, there is no precedence to worry about and all of the expressions will be evaluated from left to right. If either operand being evaluated is a String, the + operator will concatenate the two operands; if both operands are numeric, the + operator will add the two operands.

Sunday, September 7, 2014

Implement a stack using one queue

Implement stack only using one queue.



 #include<stdio.h>  
 #include<stdlib.h>  
 typedef struct queue node;  
 struct queue{  
         int d;  
         node *n;          
   
 };  
 int size=0;  
 node *f,*r;  
 void enq(int d)  
 {  
         node *t;  
         t=(node *)malloc(sizeof(node));  
         t->d=d;  
         t->n=NULL;  
         if(r)  
         {  
                 r->n=t;  
                 r=t;  
         }  
         else  
         {  
                 f=r=t;  
         }  
         size++;  
 }  
 node *deq()  
 {  
         node *t;  
         if(f)  
         {  
                 size--;  
                 t=f;  
                 f=f->n;  
                 return t;  
   
         }  
         else  
         {  
                 printf("Error");  
         }  
 }  
 void push(int d)  
 {  
         enq(d);  
   
 }  
 void pop()  
 {  
         int i=0,j=size;  
         node *t;  
         while(i<j-1)  
         {  
                 t=deq();  
                 enq(t->d);  
                 i++;  
         }  
         t=deq();  
         printf("%d ",t->d);          
   
 }  
 void main()  
 {  
         push(1);  
         push(2);  
         push(3);  
         push(4);  
         push(5);  
         pop();  
         pop();  
         pop();  
         pop();  
         pop();  
   
           
 }  

Saturday, September 6, 2014

Clone a Binary Tree with Random Pointers Given a Binary Tree where every node has following structure.
struct node {
int key;
struct node *left,*right,*random;
}
The random pointer points to any random node of the binary tree and can even point to NULL, clone the given binary tree.
You can get code in c++ Here: https://gist.github.com/gk1721/36775e17719d460ac231

Wednesday, August 27, 2014

Linkage in c

 Translation unit:
  A program in a single file - single translation unit.

sharing functions and variable btw translation units : possible if variables and function have external linkage
by default global variable and non static functions (non static variables also) has external linkage so can be shared

Ex

file1.c                                                file2.c
int a=0;                                              extern int a;   //  refering to file1.c's a
void abc()                                          void ab()
{                                                         {
                                                                  abc();        //
                                                                  notshared();   // error can't access notshared
}                                                         }
static void notshared()                      
{


}

variable and functions which has internal linkage like static functions and variables can't be accessed in other files(Translation units).

No linkage :   variables within function

Linkage :
        1. External
        2. Internal
        3. No linkage

Saturday, August 2, 2014

Sorting: bubble, selection,insertion, quick, merge, counting sort programs in c

Bubble sort:

#include<stdio.h>

// compare adjacent elements and swap if needed until whole is not sorted
int arr[]={3,8,6,1,9,6,3,1,10,7,8,5,16};
int size;
void main()
{

size=sizeof(arr)/sizeof(int);
int out[size];
int i,j;
for(i=size-1;i>=0;i--)
{
for(j=0;j<i-1;j++)
{
if(arr[j]>arr[j+1])
{
int tmp;
tmp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=tmp;
}
}
}
printf("size= %d\n",size);
for(i=0;i<size;i++)
printf("%d ",arr[i]);
}


Selection sort:

#include<stdio.h>
//  find minimum and bring it to top
int arr[]={3,8,6,1,9,6,3,1,10,7,8,5,16};
int size;
void main()
{
size=sizeof(arr)/sizeof(int);
int out[size];
int i,j;
for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{
if(arr[i]>arr[j])
{
int tmp;
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
}
printf("size= %d\n",size);
for(i=0;i<size;i++)
printf("%d ",arr[i]);
}

Insertion sort:

#include<stdio.h>
//  insert element at right place in list
int arr[]={8,3,6,1,9,6,3,1,10,7,8,5,16};
int size;
void main()
{

size=sizeof(arr)/sizeof(int);
int out[size];
int i,j,v;

for(i=1;i<size;i++)
{
v=arr[i];
j=i;
while(arr[j-1]>v&&j>=1)
{
arr[j]=arr[j-1];
j--;
}
arr[j]=v;
}
printf("size= %d\n",size);
for(i=0;i<size;i++)
printf("%d ",arr[i]);
}




------------------------------------------------------------------

Quick sort:

-----------------------------------------------------------------
#include<stdio.h>
int a[]={4,2,7,8,5,1,0,6};
int size;
void print()
{
int i;
for(i=0;i<size;i++)
printf("%d ",a[i]);
}
void swap(int left,int right)
{
int tmp=a[left];
a[left]=a[right];
a[right]=tmp;

}
int partition(int l,int r)
{
int x=a[l];
int left=l;
int right=r;
while(left<right)
{
while(a[left]<=x)
left++;
while(a[right]>x)
right--;
if(left<right)
swap(left,right);
}
a[l]=a[right];
a[right]=x;
//printf("\nPivot= %d  ",a[right]);
//print();
//printf("\n");
return right;
}
void quicksort(int l,int r)
{
// printf("%d %d\n",l,r);
int i;
if(r>l)
{

int p=partition(l,r);
quicksort(l,p-1);
quicksort(p+1,r);
}
}
void main()
{
size=sizeof(a)/sizeof(a[0]);
//print();
int p=0;
int l=0,r=size;
quicksort(l,r);
print();
}


----------------------------------------------------------

Merge Sort:

----------------------------------------------------------

#include<stdio.h>
int a[]={3,3,6,1,9,6,3,1,10,7,8,5,16};
int size;
int tmp[13];
void merge(int l,int m,int r)
{
int tmp[r-l+1];
int p=0;
int i=0,j=0;
if(a[l]>a[r])
{
for(i=m;i<r+1;i++)
tmp[p++]=a[i];
for(i=l;i<m;i++)
tmp[p++]=a[i];
}
else if(a[m]>a[m-1])
{
for(i=l;i<m;i++)
tmp[p++]=a[i];
for(i=m;i<r+1;i++)
tmp[p++]=a[i];
}
else
{
i=l;
j=m;
while((i<m)&&(j<r+1))
{
if(a[i]<a[j])
{
tmp[p++]=a[i++];
}
else if(a[i]>a[j])
{
tmp[p++]=a[j++];
}
else
tmp[p++]=a[i++];
}
if(i<m)
{
//printf("\nIn case 1\n");
int q;
for(q=i;q<m;q++)
{
tmp[p++]=a[q];
}
}
else if(j<r+1)
{
// printf("\nIn case 2p=%d\n",p);
int q;
for(q=j;q<r+1;q++)
{
tmp[p++]=a[q];
}
}

}
for(i=l;i<r+1;i++)
{
a[i]=tmp[i-l];
}
}
void mergesort(int l,int r)
{
int m;

if(r>l)
{
m=(l+r)/2;
mergesort(l,m);
mergesort(m+1,r);
merge(l,m+1,r);
}
}

void main()
{
size=sizeof(a)/sizeof(a[0]);
int l=0,r=size-1;
mergesort(l,r);
int i;
for(i=0;i<size;i++)
printf("%d ",a[i]);
}


--------------------------------------------------

Counting sort:

-------------------------------------------------
#include<stdio.h>
int a[]={1,5,6,4,8,9,3,8,0,10,16,21,6};
int size,max;
void main()
{
size=sizeof(a)/sizeof(a[0]);
int i;
int out[size];
max=0;
for(i=0;i<size;i++)
{
if(a[i]>max)
max=a[i];
}
int c[max+1];
for(i=0;i<max+1;i++)
{
c[i]=0;
}
for(i=0;i<size;i++)
{
c[a[i]]=c[a[i]]+1;
}
for(i=1;i<max+1;i++)
{
c[i]=c[i]+c[i-1];
}
for(i=size;i>=0;i--)
{
out[c[a[i]]-1]=a[i];
c[a[i]]=c[a[i]]-1;
}
for(i=0;i<size;i++)
{
printf("%d ",out[i]);
}
}