fork download
  1. // C program for insertion sort
  2. #include <math.h>
  3. #include <stdio.h>
  4.  
  5. /* Function to sort an array
  6. using insertion sort*/
  7. void insertionSort(int arr[], int n)
  8. {
  9. int i, key, j;
  10. for (i = 1; i < n; i++)
  11. {
  12. key = arr[i];
  13. j = i - 1;
  14.  
  15. /* Move elements of arr[0..i-1],
  16. that are greater than key,
  17. to one position ahead of
  18. their current position */
  19. while (j >= 0 && arr[j] > key)
  20. {
  21. arr[j + 1] = arr[j];
  22. j = j - 1;
  23. }
  24. arr[j + 1] = key;
  25. }
  26. }
  27.  
  28. // A utility function to print
  29. // an array of size n
  30. void printArray(int arr[], int n)
  31. {
  32. int i;
  33. for (i = 0; i < n; i++)
  34. printf("%d ", arr[i]);
  35. printf("\n");
  36. }
  37.  
  38. // Driver code
  39. int main()
  40. {
  41. int arr[] = {12, 11, 13, 5, 6};
  42. int n = sizeof(arr) / sizeof(arr[0]);
  43.  
  44. insertionSort(arr, n);
  45. printArray(arr, n);
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0.01s 5300KB
stdin
1
457
1
87
1
320
2
3
4
stdout
5 6 11 12 13