Mr_HO1A

Shell Sort C

Oct 23rd, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. // Include Header files
  2. #include <stdio.h>
  3.  
  4. // Declare some gloal variables
  5. int N = 7; // Size of list
  6. int arrayToSort[7];
  7.  
  8.  
  9. // Function to do shell sort
  10. int doSort(){
  11.     // Some base variables
  12.     int outer,inner;
  13.     // Find the initial interval
  14.     int interval = (N/2);
  15.     // While loop will itter untill interval becomes 0
  16.     while(interval > 0){
  17.         printf("Interval Under Process : %d\n",interval);
  18.         // This loop will check the element outer of the gap ie last element in gap
  19.         for(outer = interval;outer<N;outer++){
  20.             // Temp varaible to hold element at gap position
  21.             int tempElement = arrayToSort[outer];
  22.             inner = outer;
  23.             // While works on some conditions
  24.             // 1. Inner position must be greater then inteval position-1 because we want to check the
  25.             //      element present at gap
  26.             // 2. if the outer element is smaller then the inner elemnt then swap
  27.             while(inner > interval-1 && tempElement < arrayToSort[inner-interval]){
  28.                 arrayToSort[inner] = arrayToSort[inner-interval];
  29.                 // Decrease the inner position by interval
  30.                 inner = inner - interval;
  31.             }
  32.             // Swap the inner element also
  33.             arrayToSort[inner] = tempElement;
  34.         }
  35.         interval = (interval/2);
  36.     }
  37.     printArray();
  38. }
  39.  
  40. // Utility function to print array
  41. void printArray(){
  42.     int i = 1;
  43.     for(i = 0; i < N; i++){
  44.         printf("%d ",arrayToSort[i]);
  45.     }
  46.     printf("\n");
  47. }
  48.  
  49. int main(){
  50.     int i = 0; // Var declaration for loop
  51.     for(i=0;i<N;i++){
  52.         printf("Enter Element For Position [%d] : ",i);
  53.         scanf("%d",&arrayToSort[i]);
  54.     }
  55.     printArray();
  56.     doSort();
  57.     return 0;
  58. }
Add Comment
Please, Sign In to add comment