kucheasysa

insertion sort

Jun 6th, 2023
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. int size, i, j, key;
  5.  
  6. printf("Enter the size of the array: ");
  7. scanf("%d", &size);
  8.  
  9. int arr[size];
  10.  
  11. printf("Enter the elements of the array:\n");
  12. for (i = 0; i < size; i++) {
  13. scanf("%d", &arr[i]);
  14. }
  15.  
  16. printf("Original array: ");
  17. for (i = 0; i < size; i++) {
  18. printf("%d ", arr[i]);
  19. }
  20. printf("\n");
  21.  
  22. // Insertion Sort algorithm
  23. for (i = 1; i < size; i++) {
  24. key = arr[i];
  25. j = i - 1;
  26.  
  27. while (j >= 0 && arr[j] > key) {
  28. arr[j + 1] = arr[j];
  29. j = j - 1;
  30. }
  31.  
  32. arr[j + 1] = key;
  33. }
  34.  
  35. printf("Sorted array: ");
  36. for (i = 0; i < size; i++) {
  37. printf("%d ", arr[i]);
  38. }
  39. printf("\n");
  40.  
  41. return 0;
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment