This is the problem statement for Insertion Sort - Part 2.
In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array?Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an element with just the first element - that is already "sorted" since there's nothing to its left that is smaller than it.
In this challenge, don't print every time you move an element. Instead, print the array every time an element is "inserted" into the array in (what is currently) its correct place. Since the array composed of just the first element is already "sorted", begin printing from the second element and on.
Actually just an insertion sort implementation with ints and vector. How can I make this code faster? How can I improve this code?
#include <vector>
#include <iostream>
void print(const std::vector<int>& v) {
for (auto x : v) {
std::cout << x << ' ';
}
std::cout << '\n';
}
int main() {
int s;
std::cin >> s;
std::vector<int> sorted(s);
int i = 0;
while (std::cin && i != s) {
std::cin >> sorted[i++];
}
for (std::size_t i= 1; i < sorted.size(); ++i) {
std::size_t j = i;
for (std::size_t k = 0; k < j; ++k) {
if (sorted[j] < sorted[k]) {
std::swap(sorted[j],sorted[k]);
}
}
print(sorted);
}
}