Advertisement
tampurus

2.2 Insertion Sort

Jan 7th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.72 KB | None | 0 0
  1. /*
  2. The idea is to start iterating from the second element of array
  3. till last element and for every element insert at its correct
  4. position in the subarray before it.(like we do when we play cards)
  5. (Time Complexity:  O(N^2))
  6. */
  7. #include <stdio.h>
  8.  
  9. void InsertionSort(int arr[],int n){
  10.     for(int i=1 ; i<n ; i++){
  11.         int current = arr[i];
  12.         int j=i-1;
  13.         while(arr[j]>current && j>=0){
  14.             arr[j+1] = arr[j];
  15.             j--;
  16.         }
  17.         arr[j+1] = current;
  18.     }
  19. }
  20. int main()
  21. {
  22.     int n;
  23.     scanf("%d", &n);
  24.     int arr[n];
  25.     for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
  26.  
  27.     InsertionSort(arr,n);
  28.  
  29.     for(int i=0 ; i<n ; i++) printf("%d ",arr[i]);
  30.  
  31.     return 0;
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement