fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void print_array(int s[], int n){
  6. int i;
  7. for (i=0; i < n; i++){
  8. cout << s[i] << " ";
  9. }
  10. cout << endl;
  11. }
  12.  
  13. void insertion_sort(int s[], int n){
  14. int i, j, key;
  15. for (j = 1; j < n; j++){
  16. //display intermediate stage
  17. print_array(s, n);
  18. //insert s[j] into sorted set s[0..j-1]
  19. i = j-1;
  20. key = s[j];
  21. while ((i >= 0) && (key < s[i])){
  22. s[i+1] = s[i];
  23. i = i-1;
  24. }
  25. s[i+1] = key;
  26. }
  27. return;
  28. }
  29.  
  30. int main() {
  31. int n, i;
  32. scanf("%d", &n);
  33. int *s;
  34. s = (int *) malloc(sizeof(int) * n);
  35. for (i = 0; i < n; i++){
  36. scanf("%d", &s[i]);
  37. }
  38.  
  39. insertion_sort(s, n);
  40.  
  41. cout << "Done. Result is: " << endl;
  42. print_array(s, n);
  43.  
  44. free(s);
  45. return 0;
  46. }
Success #stdin #stdout 0s 3480KB
stdin
7  7 4 2 5 1 3 6
stdout
7 4 2 5 1 3 6 
4 7 2 5 1 3 6 
2 4 7 5 1 3 6 
2 4 5 7 1 3 6 
1 2 4 5 7 3 6 
1 2 3 4 5 7 6 
Done.  Result is: 
1 2 3 4 5 6 7