Arnab_Manna

insertion sort

Jun 13th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. //C program for insertion sort
  2. #include <math.h>
  3. #include <stdio.h>
  4. #include <conio.h>
  5.  
  6.  
  7. void insertionSortDes(int arr[], int n)
  8. {
  9.  
  10.     int i, key, j;
  11.  
  12.     for (i = 1; i < n; i++) {
  13.  
  14.         key = arr[i];
  15.  
  16.         j = i - 1;
  17.  
  18.  
  19.  
  20.         /* Move elements of arr[0..i-1], that are
  21.  
  22.           greater than key, to one position ahead
  23.  
  24.           of their current position */
  25.  
  26.         while (j >= 0 && arr[j] < key) {
  27.  
  28.             arr[j + 1] = arr[j];    
  29.  
  30.             j = j - 1;
  31.  
  32.         }
  33.  
  34.         arr[j + 1] = key;
  35.  
  36.     }
  37. }
  38.  
  39. /* Function to sort an array using insertion sort*/
  40.  
  41. void insertionSortAss(int arr[], int n)
  42. {
  43.  
  44.     int i, key, j;
  45.  
  46.     for (i = 1; i < n; i++) {
  47.  
  48.         key = arr[i];
  49.  
  50.         j = i - 1;
  51.  
  52.  
  53.  
  54.         /* Move elements of arr[0..i-1], that are
  55.  
  56.           greater than key, to one position ahead
  57.  
  58.           of their current position */
  59.  
  60.         while (j >= 0 && arr[j] > key) {
  61.  
  62.             arr[j + 1] = arr[j];    
  63.  
  64.             j = j - 1;
  65.  
  66.         }
  67.  
  68.         arr[j + 1] = key;
  69.  
  70.     }
  71. }
  72.  
  73.  
  74. // A utility function to print an array of size n
  75.  
  76. void printArray(int arr[], int n)
  77. {
  78.  
  79.     int i;
  80.     printf("\n");
  81.  
  82.     for (i = 0; i < n; i++)
  83.  
  84.         printf("%d ", arr[i]);
  85.  
  86.     printf("\n");
  87. }
  88.  
  89.  
  90. /* Driver program to test insertion sort */
  91.  
  92. int main()
  93. {
  94.     int i,arr[100],n;
  95.     char ch;
  96.     printf("enter the number of elements to be inserted : ");
  97.     scanf("%d",&n);
  98.     for(i=0;i<n;i++)
  99.     {
  100.         scanf("%d",&arr[i]);
  101.     }
  102.     printf("1> to sort in ascending order\n2>to sort in descending order");
  103.     printf("\nenter your choice");
  104.     fflush(stdin);
  105.     ch=getche();
  106.     switch(ch)
  107.     {
  108.         case '1':
  109.     insertionSortAss(arr, n);
  110.     printArray(arr, n);
  111.     break;
  112.     case '2':
  113.     insertionSortDes(arr, n);
  114.     printArray(arr, n);
  115.     break;
  116.     }
  117.     return 0;
  118. }
Add Comment
Please, Sign In to add comment