Friday, July 20, 2012

Thread Handling Example in C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <pthread.h>  
 #include <stdlib.h>  
 #include <signal.h>  
   
   
 #define ARRAYSIZE 1000  
 #define THREADS 10  
   
 void *slave(void *myid);  
   
   
 /* shared data */  
 int data[ARRAYSIZE]; /* Array of numbers to sum */  
 int sum = 0;  
 pthread_mutex_t mutex; /* mutually exclusive lock variable */  
 //int wsize;     /* size of work for each thread */   
 /* end of shared data */  
 FILE *file;  
 char filename[25];  
   
 pthread_t tid[THREADS];  
 int wsize = ARRAYSIZE/THREADS;   
 int k=1;  
   
 void pwrproc(int s)  
 {  
 k=0;  
   
 }  
   
   
   
 void *slave(void *myid)  
 {  
 int i,low,high,myresult=0;  
 printf("thread %u is created.\n",(unsigned int)pthread_self());  
 while(k) sleep(5);  
 printf("thread %u has recieved signal.\n",(unsigned int)pthread_self());  
 low=(int)myid*wsize;  
 high = low + wsize;  
   
   for (i=low;i<high;i++)  
       myresult += data[i];  
   
 fprintf(file,"The sum from %d to %d is %d \n",low,high,myresult);  
 pthread_mutex_lock(&mutex);  
 sum += myresult;  
 pthread_mutex_unlock(&mutex);  
   
 return myid;  
 }  
   
 main()  
 {  
   
   int i=0;  
   signal(SIGPWR,pwrproc);  
   
   fprintf(stdout, "Enter the File Name: ");  
   fscanf(stdin,"%s",filename);  
   file= fopen(filename,"w");  
   fprintf(file,"The process ID is %d\n",getpid());  
   fprintf(file,"The Parent Process ID is %d\n\n",getppid());  
   //fclose(file);  
   
   printf("The process ID is %d\n",getpid());  
   printf("The Parent Process ID is %d\n",getppid());  
   pthread_mutex_init(&mutex,NULL); /* initialize mutex */  
   
    /* wsize must be an integer */  
   
     for(i=0;i<ARRAYSIZE;i++)    /* initialize data[] */  
       data[i] = i+1;  
   
     
    for (i=0;i<THREADS;i++) /* create threads */  
       if (pthread_create(&tid[i],NULL,slave,(void *)i) != 0)  
          perror("Pthread_create fails");  
   
    for (i=0;i<THREADS;i++) /* join threads */  
       if (pthread_join(tid[i],NULL) != 0)  
          perror("Pthread_join fails");  
     
    printf("The sum from 1 to %i is %d\n",ARRAYSIZE,sum);  
   
   printf("The Signal is reached. Data is saved in - %s\n",filename);  
   
 }  

Hashing To Strore Intergers From File And Search In C

 This is hashing program. That stores 100000 integers from file called hashInt.txt to an array using hashing.
you can download hashInt.txt file from the following link
download
If you are in trouble in understanding this please comment me
-------------------------------------------------------------------------------------
         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include<stdio.h>  
 #include <stdlib.h>  
 #include <time.h>  
   
 #define ARR_SIZE 100000 //Number of integers in the file  
 #define TAB_SIZE 10000 //hash table size  
   
 int hash_func( int key);  
 int hash_search(int key,int value);  
   
 typedef struct hash_node{  
     
   int key;  
   struct hash_node *left;  
   struct hash_node *right;  
       
 }NODE;  
   
 int target_sum[]={231552,234756,596873,648219,726312,981237,988331,1277361,1283379};  
 NODE *hash_tab[TAB_SIZE];  
 int numbers[ARR_SIZE];  
   
 main(){  
   clock_t start = clock();  
   int i,k,key;  
   FILE *fr;  
   fr=fopen("HashInt.txt","r");  
   //intialize hash_tab array null  
   for (i=0;i<TAB_SIZE;i++){  
     hash_tab[i]=NULL;  
   }  
   i=0;  
   //get line by linee int  
   while(fscanf(fr,"%d",&key)!=EOF){  
     numbers[i]=key;  
     i++;  
     NODE *node=malloc(sizeof(NODE));  
     //get index of key  
     int index=hash_func(key);  
     //not collissions found  
     if(hash_tab[index]==NULL){  
       hash_tab[index]=node;  
       node->key=key;  
       node->right=NULL;  
       node->left=NULL;  
     }  
     //collission found  
     else{  
       NODE *p=hash_tab[index];  
       //binary search for an free node  
       while(p!=NULL){  
         if(p->key>key){  
           p=p->right;  
         }  
         else{  
           p=p->left;  
         }  
       }  
       p=node;  
       node->key=key;  
       node->right=NULL;  
       node->left=NULL;  
     }  
   }  
   fclose(fr);  
   //find target sums  
   for(k=0;k<9;k++){  
     int found=0;  
     for(i=0;i<ARR_SIZE;i++){  
       key=target_sum[k]-numbers[i];  
       if(key > 0){  
         if(hash_search(key,numbers[i])){  
           found=1;    
           printf("1");  
           break;  
         }  
       }  
     }  
     if(!found){  
       printf("0");  
     }  
   }  
   printf("\n");  
   printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);      
 }  
   
 //hash function  
 int hash_func( int key){  
   return key/100;  
 }  
 //hash search function  
 int hash_search(int key,int value){  
   int index=hash_func(key);  
   //index exeeds the array size  
   if(index>=TAB_SIZE){  
     return 0;  
   }  
     
   NODE *p=hash_tab[index];  
   //find key  
   if(p!=NULL){  
     int twise=0;  
     while(p!=NULL){  
       if(key==value){  
         if(p->key>key){  
           p=p->right;  
         }  
         else if(p->key<key){  
           p=p->left;  
         }  
         else{  
           if(twise){  
             return 0;  
           }  
           p=p->left;  
           twise++;  
         }  
       }  
       else{  
         if(p->key>key){  
           p=p->right;  
         }  
         else if(p->key<key){  
           p=p->left;  
         }  
         else{  
           return 1;  
         }  
       }  
     }  
     return 0;      
   }  
   else{  
     return 0;  
   }  
 }  

Rabin Carp String Matchin Algorithm In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int found_f=0,found_r=0,pat_val=0;  
   
 int main (){  
   system("clear");  
 while(1){  
   int i,j=0;  
   char pattern[256]={0};  
   char filename[256] = {0};  
   //Get file  
   printf("Enter path of file to read(q to exit): ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
   if(filename[0]=='q'){  
     system("clear");  
     printf("Program Exited!!!\n");  
     exit(0);  
   }  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        continue;  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
     
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
     
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
      pattern[strlen(pattern)-1]='\0';  
      for(i=0;i<strlen(pattern);i++){  
        pat_val=pat_val+pattern[i]; //ascii value of pattern  
      }  
   int ch= 0;  
   printf("\n");  
   //Get char by char from file  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[j]=ch;  
     j++;  
     find(&buffer,&pattern);  
       
      }  
      if(!found_f){  
     printf("No matching sub string found in forword comparition\n");  
   }  
   if(!found_r){  
     printf("No matching sub string found in reverse comparition\n");  
   }  
   //for(i=0;i<sz;i++){  
   //  printf("%c",buffer[i]);  
   //}  
   found_f=0;  
   found_r=0;  
   pat_val=0;  
   printf("\n");    
      fclose(file);  
  }  
   return 0;  
 }  
   
 int find(char *buffer,char *pattern){  
   int i=0,k=0,l=0;  
   if(strlen(buffer)<strlen(pattern)){  
     return 0;  
   }  
   else{  
     for(i=strlen(buffer)-strlen(pattern);i<strlen(buffer);i++){  
       int key=0;  
       for(k=i;k<(strlen(pattern)+i);k++){  
         key=key+buffer[k]; //ascii value of key  
       }  
       if(key==pat_val){  
         int m=0,n=0;  
         //Forword comparition  
         for(l=0;l<strlen(pattern);l++){  
           if(pattern[l]==buffer[i+l]){  
             n++;  
           }  
           else{  
             break;  
           }  
         }  
         if(n==strlen(pattern)){  
           printf("Matching sub string found in forword signal in %d possition.\n",i+1);  
           found_f=1;  
         }  
         n=0;  
         //Reverse comparition  
         for(l=strlen(pattern)-1;l>=0;l--,m++){  
           if(pattern[l]==buffer[i+m]){  
             n++;  
           }  
           else{  
             break;  
           }  
         }  
         if(n==strlen(pattern)){  
           printf("Matching sub string found in reverse signal in %d possition.\n",i+m);  
           found_r=1;  
         }  
       }  
     }  
   }  
 }  

Boyer Moore Algorithm Using Bad Character Rule In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int boyer_moore();  
   
 char pattern[256]={0};  
   
 int main (){  
   int i=0;  
   char filename[256] = {0};  
   //Get text file  
   printf("Enter path of file to read: ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        exit(-1);  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
   //printf("size = %d",sz);  
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
   pattern[strlen(pattern)-1]='\0';  
      int ch, word = 0;  
      i=0;  
      //put file in to array  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[i]=ch;  
     i++;  
      }  
   for(i=0;i<sz;i++){  
     printf("%c",buffer[i]);  
   }  
   printf("\n");    
      fclose(file);  
   brute_force(buffer);  
   boyer_moore(buffer);    
     return 0;  
 }  
   
 int boyer_moore(char *buffer){  
   int k=0,j=0,i=0,charcmp=0;  
   if(buffer[i]=='\0'){  
     printf("please choose a file to search\n");  
     return 0;  
   }  
   if(strlen(pattern)==0){  
     printf("please enter a pattern\n");  
     return 0;  
   }  
   if(strlen(buffer)<strlen(pattern)){  
     printf("No matching sub string found");  
     return 0;  
   }  
   printf("Boyer Moore Algorithm (Using extended bad character rule)::\n");  
   i=j=k=strlen(pattern)-1;  
   int l,found=0,not_found=1;  
   while(j<strlen(buffer)){  
     charcmp++;  
     //bad char not found  
     if(pattern[k]==buffer[i]){  
       k--; i--;  
       if(k==-1){  
         printf("\tFound matching substring at %d possition.\n",i+2);  
         j=j+strlen(pattern);  
         i=j;  
         k=strlen(pattern)-1;  
         found=1;  
       }  
     }  
     //bad char found  
     else{  
       int m=0;  
       if(k<1){  
         m=1;  
       }  
       else{  
         for(l=k-1;l>=0;l--){  
           charcmp++;  
           if(buffer[i]==pattern[l]){  
             m++;  
             not_found=0;  
             break;  
           }      
           m++;  
         }  
       }  
       j=j+m;  
       i=j;  
       k=strlen(pattern)-1;  
     }  
   }  
   if(!found){  
     printf("\tNo matching sub string found\n");  
   }  
   printf("\n\tNo of character comparitions = %d\n",charcmp);  
 }   

Brute Force String Matching Algorithm In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <string.h>  
 #include <errno.h>  
   
 int brute_force();  
   
 char pattern[256]={0};  
   
 int main (){  
   int i=0;  
   char filename[256] = {0};  
   //Get text file  
   printf("Enter path of file to read: ");  
      if (fgets(filename, sizeof(filename), stdin) == NULL){  
        fprintf(stderr, "Invalid input!\n");  
        exit(-1);  
      }  
   
   filename[strlen(filename) - 1] = '\0';  
   FILE *file = fopen(filename, "r");  
     if (!file){  
        fprintf(stderr, "Unable to open %s: %s\n",  
        filename, strerror(errno));  
        exit(-1);  
   }  
   //Get file size  
   fseek(file, 0L, SEEK_END);  
   int sz = ftell(file);  
   fseek(file, 0L, SEEK_SET);  
   //printf("size = %d",sz);  
   //create file size array  
   char buffer[sz];  
   for(i=0;i<sz;i++){  
     buffer[i]=0;  
   }  
   //Get pattern  
   printf("Enter pattern to check : ");  
      if (fgets(pattern, sizeof(pattern), stdin) == NULL){  
        fprintf(stderr, "Invalid input pattern!\n");  
        exit(-1);  
      }  
   pattern[strlen(pattern)-1]='\0';  
      int ch, word = 0;  
      i=0;  
      //put file in to array  
      while ( (ch = fgetc(file)) != EOF ){  
     buffer[i]=ch;  
     i++;  
      }  
   for(i=0;i<sz;i++){  
     printf("%c",buffer[i]);  
   }  
   printf("\n");    
      fclose(file);  
   brute_force(buffer);  
   boyer_moore(buffer);    
     return 0;  
 }  
   
 int brute_force(char *buffer){  
   int k=0,charcmp=0,j=0,i=0;  
   if(strlen(buffer)==0){  
     printf("please choose a file to search\n");  
     return 0;  
   }  
   if(strlen(pattern)==0){  
     printf("please enter a pattern\n");  
     return 0;  
   }  
   if(strlen(buffer)<strlen(pattern)){  
     printf("No matching sub string found");  
     return 0;  
   }  
   printf("Brute Force Algorithm ::\n");  
   while(i<strlen(buffer)){  
     charcmp++;  
     if(pattern[k]==buffer[i]){  
       k++; i++;  
       continue;  
     }  
     else if(pattern[k]=='\0'){  
       printf("\tFound matching substring at %d possition .\n",(i+1-strlen(pattern)));  
       k=0; j=1;  
     }  
     else{  
       i++; k=0; charcmp++;  
     }  
   }  
     if(!j){  
     printf("\tNo matching substring found\n");  
   }  
   printf("\n\tNo of character comparitions = %d \n",charcmp);  
   return 0;  
 }  

Graeffe's Root Squaring Method Using C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include<stdio.h>  
 #include<stdlib.h>  
 #include<math.h>  
   
 int graeff();  
 int main(){  
   char status[10]={0};  
   int power;  
   system("clear");  
   printf("**********************************************\n");  
   printf("\tGRAEFF'S ROOT SQUARING METHOD\n");  
   printf("**********************************************\n");  
   while(1){  
     graeff(atoi(status));  
   }      
 }  
   
 int graeff(){  
   int power,ctr,ctr1,ctr2,ctr3,i;  
     float temp=0,div=0.5,tolerance=0;  
   printf("\nEnter the Highest Power Of Polynomial (0 to exit) = ");  
     scanf("%d",&power);  
     if(power==0){  
       system("clear");  
       printf("\n\n\tTHANK YOU\n\n\n");  
       exit(0);  
     }  
     if(power<0){  
       printf("ERROR: Can not find root for minus power!!!\n");  
       return 0;  
     }  
     
   double coe[power+1],min_coe[power+1],new_coe[2*(power+1)-1],func[power+1],o_ans[power+1],n_ans[power+1];  
   for(i=0;i<=power;i++){  
     coe[i]=0;func[i]=0;min_coe[i]=0;o_ans[i]=0;n_ans[i]=0;  
   }  
   for(ctr=0;ctr<=2*power;ctr++){  
     new_coe[i]=0;  
   }  
   for(ctr=power;ctr>=0;ctr--){  
       printf("Enter the coefficient of power %d = ",ctr);  
       scanf("%lf",&coe[ctr]);  
   }  
   for(ctr=power;ctr>=0;ctr--){  
     func[ctr]=coe[ctr];  
   }  
   printf("\nEnter the Error Tolerance = ");  
     scanf("%f",&tolerance);  
   printf("\n");  
   i=1;  
   int j=1;  
     while(i){  
     //printf("Now coefficient values accoroding to the power\n");  
     //for(ctr=power;ctr>=0;ctr--){  
     //  printf("\t%dth power coefficient = %f\n",ctr,coe  
     //            [ctr]);  
     //}  
     printf("\niteration %d\n",j);  
     j++;  
     for(ctr=power;ctr>=0;ctr--){  
       min_coe[ctr]=coe[ctr];  
     }  
     for(ctr=power-1;ctr>=0;ctr=ctr-2){  
       min_coe[ctr]=(-1*min_coe[ctr]);  
     }  
     ctr2=2*power;  
     ctr3=2*power;  
     for(ctr=power;ctr>=0;ctr--){  
       for(ctr1=power;ctr1>=0;ctr1--,ctr2--){  
         new_coe[ctr2]=new_coe[ctr2]+  
             (coe[ctr]*min_coe[ctr1]);  
       }  
       ctr3--;  
       ctr2=ctr3;  
     }  
     for(ctr=power,ctr2=2*power;ctr>=0,ctr2>=0;ctr2=ctr2-2,ctr--){  
       coe[ctr]=new_coe[ctr2];  
     }  
     for(ctr=0;ctr<=2*power;ctr++){  
       new_coe[ctr]=0;  
     }  
     for(ctr=0;ctr<power;ctr++){  
         temp=fabs(coe[ctr])/fabs(coe[ctr+1]);  
         n_ans[ctr]=pow(temp,div);  
       }  
       printf("\tRoots: ");  
       for(ctr=0;ctr<power;ctr++){  
           printf("\t%f",n_ans[ctr]);  
       }  
       printf("\n\tError: ");  
       for(ctr=0;ctr<power;ctr++){  
           printf("\t%f",(n_ans[ctr]-o_ans[ctr])/o_ans[ctr]);  
       }  
       int count=0;  
       for(ctr=0;ctr<power;ctr++){  
         if((n_ans[ctr]-o_ans[ctr])/n_ans[ctr]<=tolerance){  
           count++;  
         }  
         if(j==51){  
           printf("\nRoots are not identified!!!\n");  
           return 0;  
         }  
         o_ans[ctr]=n_ans[ctr];  
         if(count==power){  
           i=0;  
         }  
       }      
     printf("\n");  
       div=div/2;  
     }  
     for(ctr=0;ctr<=power;ctr++){  
     coe[ctr]=0;  
   }  
     printf("\n");  
   for(ctr=0;ctr<power;ctr++){    
     float x1=o_ans[ctr];  
     float x2=-1*(o_ans[ctr]);      
     float y1=0;  
     float y2=0;  
     for(ctr1=0;ctr1<=power;ctr1++){      
       y1+=pow(x1,ctr1)*func[ctr1];  
     }  
     printf("When %f function = %f\t",x1,y1);  
     for(ctr1=0;ctr1<=power;ctr1++){      
       y2+=pow(x2,ctr1)*func[ctr1];  
     }  
     printf("When %f function = %f\n\n",x2,y2);  
   }  
   for(i=0;i<=power;i++){  
     coe[i]=0;func[i]=0;min_coe[i]=0;o_ans[i]=0;n_ans[i]=0;  
   }  
   for(ctr=0;ctr<=2*power;ctr++){  
     new_coe[i]=0;  
   }  
     
 }  

Radix Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
 class radix {  
   //Start counting time.  
   long start = System.nanoTime();  
   public static String[] RadixSort(long[] a) {  
     // convert from long to String  
     String[] s = new String[a.length];  
     for (int i = 0; i < a.length; i++) {  
       s[i] = Long.toString(a[i]);  
     }  
     // get the length of the longest number  
     int l = 0;  
     for (int i = 0; i < s.length; i++) {  
       int current = s[i].length();  
       if (current > l) {  
         l = current;  
       }  
     }  
     // add empty spaces to make the data of equal length  
     String current3 = "";  
     for (int i = 0; i < s.length; i++) {  
       int current2 = s[i].length();  
       for (int j = 1; j <= l-current2; j++) {  
         current3 += " ";  
       }  
       current3 += s[i];  
       s[i] = current3;  
       current3 = "";  
     }  
     // create the buckets  
     String[] tmp1 = new String[s.length];  
     String[] tmp2 = new String[s.length];  
     int tmp1i = 0;  
     int tmp2i = 0;  
     // sort the array  
     for (int i = l; i >= 1; i--) {  
       for (int j = 0; j < s.length; j++) {  
         String current = s[j].substring(i-1, i);  
         if (current.equals(" ") || current.equals("0")) {  
           tmp1[tmp1i] = s[j];  
           tmp1i++;  
         }  
         else {  
           tmp2[tmp2i] = s[j];  
           tmp2i++;  
         }  
       }  
       for (int j = 0; j < tmp1i; j++) {  
         s[j] = tmp1[j];  
       }  
       for (int j = 0; j < tmp2i; j++) {  
         int track = tmp1i;  
         s[track] = tmp2[j];  
         track++;  
       }  
       tmp1i = 0;  
       tmp2i = 0;  
     }  
     return s;  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
 public class radixsort{  
   public static void radixsort() {  
     Scanner scan = new Scanner(System.in);  
     System.out.print("How many values would you like to sort? ");  
     int length = scan.nextInt();  
     long[] a = new long[length];  
     for (int i = 0; i < length; i++) {  
       System.out.print("Enter "+ (i+1)+ " number: ");  
       a[i] = scan.nextLong();  
     }  
     radix r=new radix();  
     r.RadixSort(a);  
     //String[] s = new String[a.length];  
     //s = RadixSort(a);  
     for (int i = 0; i < a.length; i++) {  
       System.out.println(a[i]);  
     }  
     long elapsedTime = r.end - r.start;  
     System.out.println("Running time of heap sort ="+elapsedTime + " nano seconds");  
   }  
 }  

Shell Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
   
 class shell{  
   //Start counting time.  
   long start = System.nanoTime();  
   public static void shell(int[] a) {  
     int increment = a.length / 2;  //select partitions.  
     //System.out.println("\n"+"increment is "+increment+"\n");  
     while (increment > 0) {  
       System.out.println("increment is "+increment);  
       for (int i = increment; i < a.length; i++) { //select elements and sort.  
         int j = i;  
         int temp = a[i];  
         while (j >= increment && a[j - increment] > temp) { //sort selected elements.  
           a[j] = a[j - increment];  
           j = j - increment;  
   
         }  
         a[j] = temp;  
       }  
       increment=increment/2; //partition the array again  
     }  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
 public class shellsort{  
   public static void shellsort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of elements you want to sort :");  
       int length=scan.nextInt();  
       int[] arr=new int[length];  
       //System.out.println("Enter integer values you want to sort :");  
       for(int i=0;i<arr.length;i++){  
         System.out.print("Enter "+ (i+1)+ " number: ");  
         arr[i]=scan.nextInt();  
       }  
       shell sh=new shell();  
       sh.shell(arr);  
       System.out.println("\n"+ "Sorted values :");  
       for(int j=0;j<arr.length;j++){  
         System.out.print(arr[j]+",");  
       }  
       System.out.println("");  
       long elapsedTime = sh.end - sh.start;  
       System.out.println("\n"+"Running time of heap sort ="+elapsedTime + " nano seconds"+"\n");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
   
 }  

Quick Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.*;  
   
 class quick{  
   public void quickSort(int array[]){  
 // the array is sorted in ascending order  
     quickSort(array, 0, array.length - 1);       // quicksort all the elements in the array  
   }  
   
   //Start counting time.  
   long start = System.nanoTime();  
   public void quickSort(int array[], int start, int end){  
       int i = start;             // index of left-to-right scan  
       int k = end;              // index of right-to-left scan  
   
       if (end - start >= 1){          // check that there are at least two elements to sort  
           int pivot = array[start];    // set the pivot as the first element in the partition  
       System.out.println("\n"+"pivot value : "+pivot);  
           while (k > i){          // while the scan indices from left and right have not met,  
               while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first  
                   i++;                  // element greater than the pivot  
                 while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first  
                   k--;                    // element not greater than the pivot  
               if (k > i)                    // if the left seekindex is still smaller than  
                   swap(array, i, k);           // the right index, swap the corresponding elements  
           }  
           swap(array, start, k);     // after the indices have crossed, swap the last element in  
           for(int j=0;j<array.length;j++){  
         System.out.print(array[j]+",");  
       }  
       System.out.println("");     
           quickSort(array, start, k - 1); // quicksort the left partition  
           quickSort(array, k + 1, end);  // quicksort the right partition  
       }  
         else{  // if there is only one element in the partition, do not do any sorting  
           return;           // the array is sorted, so exit  
         }  
   }  
   
   public void swap(int array[], int index1, int index2){  
   // the values at indices 1 and 2 have been swapped  
     int temp = array[index1];      // store the first value in a temp  
     array[index1] = array[index2];   // copy the value of the second into the first  
     array[index2] = temp;        // copy the value of the temp into the second  
   }  
   long end = System.nanoTime();  
   //end counting time.  
 }  
   
 public class quicksort{  
   public static void quicksort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of elements you want to sort :");  
       int length=scan.nextInt();  
       int[] arr=new int[length];  
       //System.out.println("Enter integer values you want to sort :");  
       for(int i=0;i<arr.length;i++){  
         System.out.print("Enter "+ (i+1)+ " number: ");  
         arr[i]=scan.nextInt();  
       }  
       quick q=new quick();  
       q.quickSort(arr);  
       System.out.println("\n"+"Entered values after Sort :");  
       for(int j=0;j<arr.length;j++){  
         System.out.print(+arr[j]+",");  
       }  
       long elapsedTime = q.end - q.start;  
       System.out.println("");  
       System.out.println("\n"+"Running time of heap sort ="+elapsedTime + " nano seconds"+"\n");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
 }  

Heap Sort Using Java

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 import java.util.Scanner;  
 class heap{  
     private static int[] a;  
   private static int n;  
   
     public static void sort(int[] array){  
     //Initialize parsed array to variables        
     a=array;  
       n=a.length;  
       heapsort();  
     }  
     //Start counting time.  
   long start = System.nanoTime();  
     private static void heapsort(){  
       buildheap(); //build a heap using entered values.  
     //elements after building heap  
     System.out.println("\n"+"Entered Values as Heap :");  
     for(int i=0;i<a.length;i++){  
       System.out.print(a[i]+",");  
     }  
     System.out.println("");  
       while (n>1){  
           n--;  
           exchange (0, n);  
           downheap (0);  
       }  
     System.out.println("\n"+"Entered values after Heap Sort :");  
     for(int j=0;j<a.length;j++){  
       System.out.print(+a[j]+",");  
     }  
     System.out.println("\n");  
     }  
 //Building a heap using input values  
     private static void buildheap(){  
       for (int v=n/2-1; v>=0; v--)  
           downheap (v);  
     }  
 //Heap property checker  
     private static void downheap(int v){  
       int w=2*v+1;  // first descendant of v  
         while (w<n){  
           if (w+1<n)  // is there a second descendant?  
             if (a[w+1]>a[w])  
           w++;  // w is the descendant of v with maximum label  
   
           if (a[v]>=a[w])  
         return; // v has heap property  
           // otherwise  
           exchange(v, w); // exchange labels of v and w  
           v=w;    // continue  
           w=2*v+1;  
       }  
     }  
 //elements swapping method to heap property  
     private static void exchange(int i, int j){  
       int t=a[i];  
       a[i]=a[j];  
       a[j]=t;  
     }  
   long end = System.nanoTime();  
   //end counting time.  
 }  // end class heap  
   
 //new class for user input  
 public class heapsort{  
   public static void heapsort(){  
     System.out.println("");  
     Scanner scan=new Scanner(System.in);  
     try{  
       System.out.print("Enter number of values you want to sort :");  
       int length=scan.nextInt();  
       int[] arr=new int[length];  
       //System.out.println("Enter integer values you want to sort :");  
       for(int i=0;i<arr.length;i++){  
         System.out.print("Enter "+ (i+1)+ " number: ");  
         arr[i]=scan.nextInt();  
       }  
       heap hs=new heap();  
       hs.sort(arr);  
       long elapsedTime = hs.end - hs.start;  
       System.out.println("Running time of heap sort ="+elapsedTime + " nano seconds");  
     }catch(Exception e){  
       System.out.println("Error in input");  
     }  
   }  
 }  

Malloc And Free Function Implementation In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>    
     
 char memory[50000];  
 int freeMem=50000;  
   
 typedef struct{  
   int start;  
   int end;  
     
 }node;  
   
 void *NewMalloc(int size){  
   printf("\nRequested Memory= %d\t\t",size);  
   
   if(size==0){  
     printf("Can't allocate 0 size memory\n");  
     return 0;  
   }  
     
   int memsize=50000;  
   node *N=(node *)&memory[0];  
   if(freeMem >= size+sizeof(node)){  
     while(N<(node *)&memory[49999]){    
       if(N->start==0){  
         if(N->end !=0){  
           if(size+sizeof(node)< (N->end-(int)N)){  
             N->start=(int)N+8;  
             N->end=(int)N+8+size;  
             freeMem = freeMem-(size+8);  
             printf("free Mem : %d\n",freeMem);  
             return (int *)N->start;  
           }  
           else{  
             N=(node *)N->end;  
             continue;  
           }  
         }  
         else{  
           N->start=(int)N+8;  
           N->end=(int)N+8+size;  
           freeMem = freeMem-(size+8);  
           printf("free Mem : %d\n",freeMem);  
           return (int *)N->start;  
         }  
       }  
           
       N = (node *)N->end;  
     }  
   }  
   else{  
     printf("there is not enaugh space to allocate required memory\n");  
     return 0;  
   }  
 }  
 void NewFree(void * p){  
   node *ptr = (node *)p;  
   ptr--;  
    freeMem=freeMem+(ptr->end - ptr->start)+sizeof(node);  
      if(ptr->start != 0){  
     printf("\nfreed memory size : %d\t",ptr->end - ptr->start);  
        
        printf("Now available memory : %d ",freeMem);  
     ptr->start = 0;   
        printf("\nMemory Freed...\n");  
   }  
   else{  
     printf("\nThere is no such allocated memory for this address!!!!!\n");  
   }  
     
 }   
 int main(){  
   
   char *str;  
   str=NewMalloc(10000);  
   printf("address : %d\n",(int)str);    
   
   char *str1;  
   str1=NewMalloc(0);  
   printf("address : %d\n",(int)str1);    
   
   char *str2;  
   str2=NewMalloc(10000);  
   printf("address : %d\n",(int)str2);    
     
   char *str3;  
   str3=NewMalloc(10000);  
   printf("address : %d\n",(int)str3);    
   
   char *str4;  
   str4=NewMalloc(10000);  
   printf("address : %d\n",(int)str4);  
 NewFree(str2);  
   char *str5;  
   str5=NewMalloc(12000);  
   printf("address : %d\n",(int)str5);    
   return 0;  
 }  

My Own Shell for Linux

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>  
 #include <stdlib.h>  
 #include <unistd.h>  
 #include <string.h>  
 #include <errno.h>  
 #include <sys/types.h>  
   
 /*method to parse thi input to argv and store null  
   point of the white spaces of the input*/  
 void parse(char *input, char **argv){  
   while (*input != '\0') {  //  
        while (*input == ' ' || *input == '\t' || *input == '\n'){  
             *input++ = '\0';  
     }  
        *argv++ = input;  
        while (*input != '\0' && *input != ' ' && *input != '\t' && *input != '\n'){  
             input++;  
     }  
   }  
      *argv = '\0';  
 }  
   
 //check method to check the input  
 int check(char *input){  
   int i = 0;  
   for(i = 0; i < strlen(input); i++){  
      if(input[i] == '|'){  //if input[i] is |(pipe)  
       return i;  //return i  
     }  
   
   }  
   return 0;  //otherwise return 0  
 }  
   
 //execute the command if there is pipe  
 int pipexec(char input[32],int i){    
   char *input2 = &input[i + 1];  //assign the address of input[i+1] to input2 pointer  
   input[i] = '\0';    //assign input[i] as a null point  
   int pid[2];    
   int retvalexec;      
           
   if(pipe(pid) == -1){    //if pipe is not created  
     perror("pipe call error");  
     exit(1);       
   }  
     
   char *arr[32];  
   if(fork()){    //create a new process and if it is parent  
     close(1);  //close the stdin of that process  
     dup(pid[1]);  //duplicate that to pid[1]  
     close(pid[0]);  //close the stdou of pid  
     parse(input, arr); //method calling  
     retvalexec=execvp(arr[0], arr); //execute and return the value to the retvalexec  
     if(retvalexec) {  //if retvalexec is not 0  
           puts(strerror(errno)); //print string of the error number   
           exit(0);    //exit  
         }   
           
   }else{    //if it is child process  
     close(0);  //close the stdou of that process  
     dup(pid[0]);   //duplicate that to pid[0]  
     close(pid[1]);  //close the stdin of pid  
     parse(input2, arr);  //method calling  
     retvalexec=execvp(arr[0], arr);  //execute and return the value to the retvalexec  
       
     if(retvalexec) {  //if retvalexec is not 0  
           puts(strerror(errno)); //print string of the error number   
           exit(0);    //exit  
         }                    
   }          
   return 0;  
 }  
   
 //execute normally if there is not pipe  
 int execute(char input[32],char *argv[32]){  
   parse(input, argv); //method calling  
   if(execvp(argv[0], argv)!=0) {  //if retvalexec is not 0  
         puts(strerror(errno)); //print string of the error number   
         exit(0);    //exit  
      }    
   return 0;  
 }  
   
 //main method starts here  
 int main(){  
   char input[32];  //to store user input  
   char *argv[32];  //to store input and null points  
   pid_t pid;  
   
   printf("\n\n\n");  
     
   while (1) {    
     printf("MOSH $ ");  
     gets(input);  //get the user input to input char array  
   
     if (strcmp(input, "exit") == 0){  //compare the input  
             exit(0);      //if it is "exit" exit from mosh  
     }  
        pid = fork();    //create a new process and return the value to pid  
         
     if (pid){  //if parent process runs  
           wait(0);  //wait until child finished  
       }else{    //if child process runs        
       int i = 0;  
       i = check(input);  //check the input assign return value to i  
       if(i){      //if input has | symbol  
         pipexec(input,i);  
       }else{    //if input has not | symbol  
         execute(input,argv);                
       }  
       }  
     }  
     return 0;  //return 0 to sending program executed correctly  
 }