Mazamin

insertionSort

Nov 20th, 2019
670
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. /*
  2.  * File:   main.c
  3.  * Author: Gerardo Cicalese
  4.  *
  5.  * Created on 18 novembre 2019, 14.22
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <time.h>
  11.  
  12. typedef int Info;
  13.  
  14. void insertionSort(Info *, int);
  15. void insertInOrder(Info *, int, Info);
  16. void swap(Info *, Info *);
  17. int compare(Info, Info);
  18.  
  19. int main(void)
  20. {
  21.     srand(time(NULL));
  22.     Info array[10];
  23.    
  24.     for(int i=0; i<10; ++i)
  25.         array[i] = rand()%100;
  26.    
  27.     for(int i=0; i<10; ++i)
  28.         printf("%d\t", array[i]);
  29.    
  30.     printf("\nSorting...\n");
  31.     insertionSort(array, 10);
  32.    
  33.     for(int i=0; i<10; ++i)
  34.         printf("%d\t", array[i]);
  35.    
  36.     return 0;
  37. }
  38.  
  39. void insertionSort(Info * array, int len)
  40. {
  41.     for(int i = 1; i < len; ++i)
  42.         insertInOrder(array, i, array[i]);
  43. }
  44.  
  45. void insertInOrder(Info * array, int len, Info item)
  46. {
  47.     int pos = len;
  48.    
  49.     for(; pos > 0 && 1 == compare(array[pos - 1], item); --pos);
  50.    
  51.     for(int i = len; i > pos; --i)
  52.         array[i] = array[i - 1];
  53.    
  54.     array[pos] = item;
  55. }
  56.  
  57. void swap(Info * a, Info * b)
  58. {
  59.     Info temp = *a;
  60.     *a = *b;
  61.     *b = temp;
  62. }
  63.  
  64. int compare(Info a, Info b)
  65. {
  66.     if(a == b)
  67.         return 0;
  68.    
  69.     if(a > b)
  70.         return 1;
  71.    
  72.     return -1;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment