C Program to Sort an Array Using Insertion Sort



In this program, we will implement Insertion Sort



  1. // C program to sort an array using Insertion Sort
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int n, arr[100], i, j, t;
  6. printf("Enter number of element: ");
  7. scanf("%d", &n);
  8. printf("Enter elements: " );
  9. for (i = 0; i < n; i++)
  10. {
  11. scanf("%d", &arr[i]);
  12. }
  13. for (i = 1 ; i <= n - 1; i++)
  14. {
  15. j = i;
  16. while ( j > 0 && arr[j-1] > arr[j])
  17. {
  18. t = arr[j];
  19. arr[j] = arr[j-1];
  20. arr[j-1] = t;
  21. j--;
  22. }
  23. }
  24. printf("Sorted array: ");
  25. for (i = 0; i <= n - 1; i++)
  26. {
  27. printf("%d ", arr[i]);
  28. }
  29. return 0;
  30. }

Output
Output!
download android app

Popular C Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube