fork download
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Function to sort an array using the Insertion Sort algorithm
  6. void insertion_sort(int n, int arr[])
  7. {
  8. // Display the sorting method being used
  9. cout << "insertion sort" << endl;
  10.  
  11. // Start from the second element (index 1)
  12. for(int j = 1; j < n; j++)
  13. {
  14. // Store the current element to be inserted
  15. int key = arr[j];
  16.  
  17. // Index of the previous element
  18. int i = j - 1;
  19.  
  20. // Move elements greater than key one position to the right
  21. while(i >= 0 && arr[i] > key)
  22. {
  23. arr[i + 1] = arr[i]; // Shift element right
  24. i--;
  25. }
  26.  
  27. // Insert the key into its correct sorted position
  28. arr[i + 1] = key;
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. // Size of the array
  35. int n = 5;
  36.  
  37. // Initialize the array with unsorted values
  38. int arr[5] = {5, 3, 6, 7, 1};
  39.  
  40. // Call the insertion sort function
  41. insertion_sort(n, arr);
  42.  
  43. // Print the sorted array
  44. for(int i = 0; i < n; i++)
  45. {
  46. cout << arr[i] << " ";
  47. }
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
insertion sort
1 3 5 6 7