Challenge: Insertion Sort Steps
Completed
Sort n numbers with insertion sort. After inserting each item (from the second on), print the vector.
Input
Line 1: n (n ≥ 2). Line 2: n whole numbers.
Output
n − 1 lines.
Example
Input
4 7 3 5 1
Output
3 7 5 1 3 5 7 1 1 3 5 7
Editor
C++
Hints
Take v[i] as the card.
Shift bigger items right, then drop the card in the gap.
Solution explanation
After step i, the first i + 1 items are sorted.
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
for (int i = 1; i < n; i++) {
int card = v[i], j = i - 1;
while (j >= 0 && v[j] > card) { v[j + 1] = v[j]; j--; }
v[j + 1] = card;
for (int k = 0; k < n; k++) cout << v[k] << (k + 1 < n ? " " : "\n");
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module