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