void insertion_sort(std::vector<int> &vec) {
int i{0}, j{0};
for (i = 1; i < vec.size(); i++) {
auto at_begin = i;
for (j = i - 1; j >= 0; j--) {
if (vec[i] < vec[j]) {
std::swap(vec[i--], vec[j]);
}
}
i = at_begin;
}
}
``` is this code correct?
#insertion sort
8 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
if it is
void shell_sort(std::vector<int> &vec) {
for (int gap = vec.size() / 2; gap > 0; gap /= 2) {
for (int i = gap; i < vec.size(); i++) {
auto at_begin = i;
for (int j = i - 1; j >= gap; j--) {
if (vec[i] < vec[j]) {
std::swap(vec[i--], vec[j]);
}
}
i = at_begin;
}
}
}
why does this shell sort function doesnt sort the first element but sorts other
1 -1 -1 1 3 4 15 20 39
from
std::vector<int> a{1,-1, 20, 15, 3, 4, 1, -1, 39};
Try testing it 😛
Make some test cases
!debugger
@marsh heart
Have you tried stepping through your code line by line in a debugger?
If you don't know how to use a debugger or don't have one set up, we highly recommend taking the time to do so.
Debuggers are immensely helpful tools for figuring out where problems emerge in code and especially when you're first learning it can help you build intuition and understanding for reasoning through code.
Resources:
- Getting started with debugging in Visual Studio
- Getting started with debugging in vscode on windows
- Getting started with debugging in vscode on linux
- If your IDE isn't listed here, you can find a guide for your IDE online
Given how simple an insertion sort can be (https://books.google.com/books?id=kse_7qbWbjsC&pg=PA116&redir_esc=y#v=onepage&q&f=false), I suspect the answer is no.