Advertisement
Mary_99

insertion sort

Jan 9th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* insertion sort */
  5.  
  6. void insertion_sort(int arr[], int n)
  7. {
  8.     for(int i = 0; i < n; i++)
  9.         {
  10.         int bufor = arr[i]; //bufor stores the element whose left side is checked
  11.         int j = i;
  12.          //loop checks whether the element on left side is greater or smaller than the current element
  13.         while(j > 0 && bufor < arr[j-1])
  14.         {
  15.             arr[j] = arr[j-1]; // moving the left side element to one position forward
  16.             j = j - 1;
  17.         }
  18.         arr[j] = bufor; //moving current element to its correct position
  19.     }
  20. }
  21.  
  22. int main(int argc, char *argv[])
  23. {
  24.     int A [100];
  25.     int i, n ,j ,key;
  26.  
  27.     printf("Enter the number of elements you want to sort =   ");
  28.     scanf("%d", &n);
  29.  
  30.     for (i=0; i<n; i++)
  31.     {
  32.     printf("\nEnter the element %d:   ", i+1);
  33.     scanf("%d", &A[i]); // not put space after d :>
  34.     fflush(stdin);
  35.     }
  36.    
  37.     insertion_sort(A, n);
  38.  
  39.     for (i=0; i<n; i++)
  40.     {
  41.         printf("%d\n", A[i]);
  42.     }
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement