Advertisement
micha_b

shellsort.c

Nov 12th, 2022
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.08 KB | Source Code | 0 0
  1. /*
  2.  *   C Program that uses pointers to sort an array
  3.  *   in ascending order using Shell Sort
  4.  */    
  5.  
  6. #include <exec/types.h>
  7. #include <dos/dos.h>
  8.  
  9. #include <proto/exec.h>
  10. #include <proto/dos.h>
  11.  
  12. #include <stdio.h>
  13.  
  14. /* proto types */
  15. void swap(int *a, int *b);
  16. void shellsort(int arr[], int nums);
  17.  
  18.  
  19. void swap(int *a, int *b)
  20. {
  21.     *a=*a + *b;
  22.     *b=*a - *b;
  23.     *a=*a - *b;
  24.  
  25.     return ;
  26. }
  27.  
  28. // Function definition of sort array using shell sort
  29. void shellsort(int arr[], int nums)
  30. {  
  31.     int i = 0, j = 0, k = 0;
  32.    
  33.     // i -> gap/interval  
  34.     for (i = nums / 2; i > 0; i = i / 2)
  35.     {  
  36.         // Traverse j till we reach the end of the sublist.
  37.         for (j = i; j < nums; j++)
  38.         {
  39.             for(k = j - i; k >= 0; k = k - i)
  40.             {
  41.                 if (arr[k+i] >= arr[k])
  42.                 {  
  43.                     break;  
  44.                 }  
  45.                 else
  46.                 {
  47.                     swap(&arr[k], &arr[k+i]);
  48.                 }  
  49.             }
  50.         }  
  51.     }
  52.  
  53.     return ;
  54.  
  55. }    
  56.  
  57. int main()
  58. {
  59.     int nums = 0;
  60.     int k = 0;
  61.    
  62.     #ifdef __SASC
  63.         int arr[256];
  64.     #else
  65.         int arr[nums];
  66.     #endif
  67.    
  68.  
  69.     printf("Enter total no. of elements : ");  
  70.     #ifdef __SASC
  71.         printf("(max. allowed array size is 256)");
  72.     #endif
  73.     scanf("%d", &nums);  
  74.    
  75.     #ifdef __SASC
  76.         if (nums > 256)
  77.         {
  78.             puts("Sorry, that's too much for me!");
  79.             puts("Yours sincerely,\nSAS/C");
  80.             return 0;
  81.         }
  82.     #endif      
  83.  
  84.     printf("Enter the array: \n");
  85.  
  86.     //scan the array elements.
  87.     for (k =  0 ; k < nums; k++)
  88.     {  
  89.         scanf("%d", &arr[k]);
  90.     }      
  91.  
  92.     //Call the function of shell sort, bypassing the array base pointer to the first element.
  93.     shellsort(arr, nums);      
  94.  
  95.     // After the sorting the array is
  96.     printf("Sorted array is:  \n");
  97.  
  98.     for (k = 0; k < nums; k++)
  99.     {
  100.         printf("%d ", arr[k]);
  101.     }  
  102.  
  103.     puts("\nThats it!\n");
  104.     return 0;
  105. }
  106.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement