Advertisement
Extremum

Sor.c

May 25th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void CountingSort(int n, int arr[], int sortArr[]);
  6. void RadixSort(int arr[],int num);
  7.  
  8. void print(int *a, int n) {
  9.     int i;
  10.     for (i = 0; i < n; i++)
  11.       printf("%d ", a[i]);
  12. }
  13.  
  14. int main(int argc,char *argv[])
  15. {
  16.   int type=0;
  17.   if(argc==1){
  18.     printf("Select size of array with numbers starting from 1\n");
  19.     printf("Select sorting type\n c : Counting Sort\n r : Radix Sort\n");
  20.     exit(0);
  21.   }
  22.   else if (argc==2){
  23.     printf("Two arguments needed\n");
  24.     exit(0);
  25.   }
  26.   else if (argc==3){
  27.     if(strstr(argv[2],"c")!=0){
  28.         printf("Selected type: Counting Sort\n");
  29.         type=1;
  30.  
  31.     }
  32.     else if(strstr(argv[2],"r")!=0){
  33.         printf("Selected type: Radix Sort\n");
  34.         type=2;
  35.     }
  36.   }
  37.   int num,i;
  38.   int *arr,*sortArr;
  39.   num=atoi(argv[1]);
  40.     arr = (int *)malloc(num * sizeof(int));
  41.     sortArr = (int *)malloc(num * sizeof(int));
  42.     for(i=0;i<num;i++){
  43.          scanf("%d", &arr[i]);
  44.     }
  45.    if(type==1){
  46.     CountingSort(num,arr,sortArr);
  47.       print(sortArr,num);
  48.     }
  49.    if(type==2){
  50.     RadixSort(arr,num);
  51.       print(arr,num);
  52.    }      
  53. }
  54.  
  55. void CountingSort(int num, int arr[], int sortArr[])
  56. {
  57.     int k;
  58.     for(int i=0;i<num;i++)
  59.     {
  60.         k=0;
  61.         for(int j=0;j<num;j++)
  62.         {
  63.             if(arr[i]>arr[j])
  64.                 k++;
  65.         }
  66.         sortArr[k] = arr[i];
  67.     }
  68. }
  69.  
  70. void RadixSort(int arr[],int num ){
  71.   int bucket[10][5],buck[10],b[10];
  72.   int i,j,k,l,n=0,div=1,large,passes;
  73.    large=arr[0];
  74.     for(i=0;i<num;i++)
  75.     {
  76.         if(arr[i]>large){
  77.             large=arr[i];
  78.         }
  79.         while(large>0){
  80.             n++;
  81.             large=large/10;
  82.         }
  83.         for(passes=0;passes<n;passes++){
  84.             for(k=0;k<10;k++){
  85.                 buck[k]=0;
  86.             }
  87.             for(i=0;i<num;i++){
  88.                 l=((arr[i]/div)%10);
  89.                 bucket[l][buck[l]++]=arr[i];
  90.             }  
  91.             i=0;
  92.             for(k=0;k<10;k++){
  93.                 for(j=0;j<buck[k];j++)
  94.                 {
  95.                     arr[i++]=bucket[k][j];
  96.                 }
  97.             }
  98.             div*=10;
  99.         }
  100.     }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement