Divide and conquer merge sorting not working
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
Here is the code. I simply did a merge sorting using a Divide and Conquer algorithm but it doesn't work and i haven't found why. I'm passing an unordered vector, 0 and vector.size()
to the mergeSort
function.
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end);
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right);
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right);
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end)
{
T value = T();
int i;
int j;
for(i = start + 1; i < end; ++i)
{
value = vec[i];
for(j = i - 1; j >= 0 && !(vec[j] < value); --j)
vec[j + 1] = vec[j];
vec[j + 1] = value;
}
}
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right)
{
int length = right - left;
if(length <= 3)
directInsertion(vec, left, right);
else
{
int middle = left + (length >> 1);
mergeSort(vec, left, middle);
mergeSort(vec, middle, right);
merge(vec, left, middle, right);
}
}
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right)
{
int length = right - left;
int p = left;
int q = middle + 1;
std::vector<T> tmp;
for(size_t l = 0; l < length; ++l) {
if (p <= middle && (q >= right || vec.at(p) <= vec.at(q)))
tmp.push_back(vec.at(p++));
else
tmp.push_back(vec.at(q++));
}
for(size_t l = 0; l < length; ++l)
vec.at(left + l) = tmp.at(l);
}
void printMessage(bool passed, const char* message)
{
if(passed)
std::cout << message << "............... PASS" << std::endl;
else
std::cout << message << "............... FAIL" << std::endl;
}
void printVector(std::vector<int>& v)
{
std::cout << "[";
for(auto i: v)
std::cout << " " << i << " ,";
std::cout << "]";
}
int main()
{
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> orderedVector = v;
std::vector<int> aux;
bool passed = true;
do {
aux = v;
mergeSort(aux, 0, aux.size());
if(aux != orderedVector)
{
printVector(aux);
std::cout << " != ";
printVector(orderedVector);
std::cout << std::endl;
passed = false;
}
} while(std::next_permutation(v.begin(), v.end()) && passed);
printMessage(passed, "MERGE SORT");
}
c++ algorithm sorting debugging mergesort
|
show 12 more comments
Here is the code. I simply did a merge sorting using a Divide and Conquer algorithm but it doesn't work and i haven't found why. I'm passing an unordered vector, 0 and vector.size()
to the mergeSort
function.
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end);
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right);
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right);
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end)
{
T value = T();
int i;
int j;
for(i = start + 1; i < end; ++i)
{
value = vec[i];
for(j = i - 1; j >= 0 && !(vec[j] < value); --j)
vec[j + 1] = vec[j];
vec[j + 1] = value;
}
}
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right)
{
int length = right - left;
if(length <= 3)
directInsertion(vec, left, right);
else
{
int middle = left + (length >> 1);
mergeSort(vec, left, middle);
mergeSort(vec, middle, right);
merge(vec, left, middle, right);
}
}
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right)
{
int length = right - left;
int p = left;
int q = middle + 1;
std::vector<T> tmp;
for(size_t l = 0; l < length; ++l) {
if (p <= middle && (q >= right || vec.at(p) <= vec.at(q)))
tmp.push_back(vec.at(p++));
else
tmp.push_back(vec.at(q++));
}
for(size_t l = 0; l < length; ++l)
vec.at(left + l) = tmp.at(l);
}
void printMessage(bool passed, const char* message)
{
if(passed)
std::cout << message << "............... PASS" << std::endl;
else
std::cout << message << "............... FAIL" << std::endl;
}
void printVector(std::vector<int>& v)
{
std::cout << "[";
for(auto i: v)
std::cout << " " << i << " ,";
std::cout << "]";
}
int main()
{
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> orderedVector = v;
std::vector<int> aux;
bool passed = true;
do {
aux = v;
mergeSort(aux, 0, aux.size());
if(aux != orderedVector)
{
printVector(aux);
std::cout << " != ";
printVector(orderedVector);
std::cout << std::endl;
passed = false;
}
} while(std::next_permutation(v.begin(), v.end()) && passed);
printMessage(passed, "MERGE SORT");
}
c++ algorithm sorting debugging mergesort
6
This is a problem that should be solved by debugging. Using your favorite debugger (and/or) IDE, step through the code line by line, each time formulating your expected result of a step before letting the code do it. If the line of code does something else than you expect, investigate there. Debugging like this is a crucial skill to have as a programmer, so use this opportunity!
– Max Langhof
Jan 4 at 13:31
3
Did you run your code using a debugger? Compare your code with the implementation here. What is the difference? Also, claiming that a function is working, thus you won't post the function many times ends up wasting a lot of time if the function that isn't posted is the faulty function.
– PaulMcKenzie
Jan 4 at 13:31
5
@Repikas If i weren't 100% sure that directInsertion is working i would have post it -- If I had a dollar for every post where the unposted "working code" was the actual problem, I would be a rich man. Please post a Minimal, Complete, and Verifiable example.
– PaulMcKenzie
Jan 4 at 13:46
3
I fixed the missing includes, missing print functions, and reordered the functions so it would run. Your example should run without my having to do that. I got a vector index out of range. I'm not saying where because you should get the same when you debug it, and that will be a lot more useful to you.
– Kenny Ostrom
Jan 4 at 14:19
3
also avoid name conflicts. "vector" isn't a wise choice for a variable name. But nice test case -- I would recommend you make it as small as you can and still get the error, so it will be easy to debug.
– Kenny Ostrom
Jan 4 at 14:28
|
show 12 more comments
Here is the code. I simply did a merge sorting using a Divide and Conquer algorithm but it doesn't work and i haven't found why. I'm passing an unordered vector, 0 and vector.size()
to the mergeSort
function.
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end);
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right);
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right);
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end)
{
T value = T();
int i;
int j;
for(i = start + 1; i < end; ++i)
{
value = vec[i];
for(j = i - 1; j >= 0 && !(vec[j] < value); --j)
vec[j + 1] = vec[j];
vec[j + 1] = value;
}
}
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right)
{
int length = right - left;
if(length <= 3)
directInsertion(vec, left, right);
else
{
int middle = left + (length >> 1);
mergeSort(vec, left, middle);
mergeSort(vec, middle, right);
merge(vec, left, middle, right);
}
}
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right)
{
int length = right - left;
int p = left;
int q = middle + 1;
std::vector<T> tmp;
for(size_t l = 0; l < length; ++l) {
if (p <= middle && (q >= right || vec.at(p) <= vec.at(q)))
tmp.push_back(vec.at(p++));
else
tmp.push_back(vec.at(q++));
}
for(size_t l = 0; l < length; ++l)
vec.at(left + l) = tmp.at(l);
}
void printMessage(bool passed, const char* message)
{
if(passed)
std::cout << message << "............... PASS" << std::endl;
else
std::cout << message << "............... FAIL" << std::endl;
}
void printVector(std::vector<int>& v)
{
std::cout << "[";
for(auto i: v)
std::cout << " " << i << " ,";
std::cout << "]";
}
int main()
{
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> orderedVector = v;
std::vector<int> aux;
bool passed = true;
do {
aux = v;
mergeSort(aux, 0, aux.size());
if(aux != orderedVector)
{
printVector(aux);
std::cout << " != ";
printVector(orderedVector);
std::cout << std::endl;
passed = false;
}
} while(std::next_permutation(v.begin(), v.end()) && passed);
printMessage(passed, "MERGE SORT");
}
c++ algorithm sorting debugging mergesort
Here is the code. I simply did a merge sorting using a Divide and Conquer algorithm but it doesn't work and i haven't found why. I'm passing an unordered vector, 0 and vector.size()
to the mergeSort
function.
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end);
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right);
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right);
template<typename T>
void directInsertion(std::vector<T>& vec, int start, int end)
{
T value = T();
int i;
int j;
for(i = start + 1; i < end; ++i)
{
value = vec[i];
for(j = i - 1; j >= 0 && !(vec[j] < value); --j)
vec[j + 1] = vec[j];
vec[j + 1] = value;
}
}
template<typename T>
void mergeSort(std::vector<T>& vec, int left, int right)
{
int length = right - left;
if(length <= 3)
directInsertion(vec, left, right);
else
{
int middle = left + (length >> 1);
mergeSort(vec, left, middle);
mergeSort(vec, middle, right);
merge(vec, left, middle, right);
}
}
template<typename T>
void merge (std::vector<T>& vec, int left, int middle, int right)
{
int length = right - left;
int p = left;
int q = middle + 1;
std::vector<T> tmp;
for(size_t l = 0; l < length; ++l) {
if (p <= middle && (q >= right || vec.at(p) <= vec.at(q)))
tmp.push_back(vec.at(p++));
else
tmp.push_back(vec.at(q++));
}
for(size_t l = 0; l < length; ++l)
vec.at(left + l) = tmp.at(l);
}
void printMessage(bool passed, const char* message)
{
if(passed)
std::cout << message << "............... PASS" << std::endl;
else
std::cout << message << "............... FAIL" << std::endl;
}
void printVector(std::vector<int>& v)
{
std::cout << "[";
for(auto i: v)
std::cout << " " << i << " ,";
std::cout << "]";
}
int main()
{
std::vector<int> v = {1, 2, 3, 4};
std::vector<int> orderedVector = v;
std::vector<int> aux;
bool passed = true;
do {
aux = v;
mergeSort(aux, 0, aux.size());
if(aux != orderedVector)
{
printVector(aux);
std::cout << " != ";
printVector(orderedVector);
std::cout << std::endl;
passed = false;
}
} while(std::next_permutation(v.begin(), v.end()) && passed);
printMessage(passed, "MERGE SORT");
}
c++ algorithm sorting debugging mergesort
c++ algorithm sorting debugging mergesort
edited Jan 4 at 21:10
Repikas
asked Jan 4 at 13:25
RepikasRepikas
139110
139110
6
This is a problem that should be solved by debugging. Using your favorite debugger (and/or) IDE, step through the code line by line, each time formulating your expected result of a step before letting the code do it. If the line of code does something else than you expect, investigate there. Debugging like this is a crucial skill to have as a programmer, so use this opportunity!
– Max Langhof
Jan 4 at 13:31
3
Did you run your code using a debugger? Compare your code with the implementation here. What is the difference? Also, claiming that a function is working, thus you won't post the function many times ends up wasting a lot of time if the function that isn't posted is the faulty function.
– PaulMcKenzie
Jan 4 at 13:31
5
@Repikas If i weren't 100% sure that directInsertion is working i would have post it -- If I had a dollar for every post where the unposted "working code" was the actual problem, I would be a rich man. Please post a Minimal, Complete, and Verifiable example.
– PaulMcKenzie
Jan 4 at 13:46
3
I fixed the missing includes, missing print functions, and reordered the functions so it would run. Your example should run without my having to do that. I got a vector index out of range. I'm not saying where because you should get the same when you debug it, and that will be a lot more useful to you.
– Kenny Ostrom
Jan 4 at 14:19
3
also avoid name conflicts. "vector" isn't a wise choice for a variable name. But nice test case -- I would recommend you make it as small as you can and still get the error, so it will be easy to debug.
– Kenny Ostrom
Jan 4 at 14:28
|
show 12 more comments
6
This is a problem that should be solved by debugging. Using your favorite debugger (and/or) IDE, step through the code line by line, each time formulating your expected result of a step before letting the code do it. If the line of code does something else than you expect, investigate there. Debugging like this is a crucial skill to have as a programmer, so use this opportunity!
– Max Langhof
Jan 4 at 13:31
3
Did you run your code using a debugger? Compare your code with the implementation here. What is the difference? Also, claiming that a function is working, thus you won't post the function many times ends up wasting a lot of time if the function that isn't posted is the faulty function.
– PaulMcKenzie
Jan 4 at 13:31
5
@Repikas If i weren't 100% sure that directInsertion is working i would have post it -- If I had a dollar for every post where the unposted "working code" was the actual problem, I would be a rich man. Please post a Minimal, Complete, and Verifiable example.
– PaulMcKenzie
Jan 4 at 13:46
3
I fixed the missing includes, missing print functions, and reordered the functions so it would run. Your example should run without my having to do that. I got a vector index out of range. I'm not saying where because you should get the same when you debug it, and that will be a lot more useful to you.
– Kenny Ostrom
Jan 4 at 14:19
3
also avoid name conflicts. "vector" isn't a wise choice for a variable name. But nice test case -- I would recommend you make it as small as you can and still get the error, so it will be easy to debug.
– Kenny Ostrom
Jan 4 at 14:28
6
6
This is a problem that should be solved by debugging. Using your favorite debugger (and/or) IDE, step through the code line by line, each time formulating your expected result of a step before letting the code do it. If the line of code does something else than you expect, investigate there. Debugging like this is a crucial skill to have as a programmer, so use this opportunity!
– Max Langhof
Jan 4 at 13:31
This is a problem that should be solved by debugging. Using your favorite debugger (and/or) IDE, step through the code line by line, each time formulating your expected result of a step before letting the code do it. If the line of code does something else than you expect, investigate there. Debugging like this is a crucial skill to have as a programmer, so use this opportunity!
– Max Langhof
Jan 4 at 13:31
3
3
Did you run your code using a debugger? Compare your code with the implementation here. What is the difference? Also, claiming that a function is working, thus you won't post the function many times ends up wasting a lot of time if the function that isn't posted is the faulty function.
– PaulMcKenzie
Jan 4 at 13:31
Did you run your code using a debugger? Compare your code with the implementation here. What is the difference? Also, claiming that a function is working, thus you won't post the function many times ends up wasting a lot of time if the function that isn't posted is the faulty function.
– PaulMcKenzie
Jan 4 at 13:31
5
5
@Repikas If i weren't 100% sure that directInsertion is working i would have post it -- If I had a dollar for every post where the unposted "working code" was the actual problem, I would be a rich man. Please post a Minimal, Complete, and Verifiable example.
– PaulMcKenzie
Jan 4 at 13:46
@Repikas If i weren't 100% sure that directInsertion is working i would have post it -- If I had a dollar for every post where the unposted "working code" was the actual problem, I would be a rich man. Please post a Minimal, Complete, and Verifiable example.
– PaulMcKenzie
Jan 4 at 13:46
3
3
I fixed the missing includes, missing print functions, and reordered the functions so it would run. Your example should run without my having to do that. I got a vector index out of range. I'm not saying where because you should get the same when you debug it, and that will be a lot more useful to you.
– Kenny Ostrom
Jan 4 at 14:19
I fixed the missing includes, missing print functions, and reordered the functions so it would run. Your example should run without my having to do that. I got a vector index out of range. I'm not saying where because you should get the same when you debug it, and that will be a lot more useful to you.
– Kenny Ostrom
Jan 4 at 14:19
3
3
also avoid name conflicts. "vector" isn't a wise choice for a variable name. But nice test case -- I would recommend you make it as small as you can and still get the error, so it will be easy to debug.
– Kenny Ostrom
Jan 4 at 14:28
also avoid name conflicts. "vector" isn't a wise choice for a variable name. But nice test case -- I would recommend you make it as small as you can and still get the error, so it will be easy to debug.
– Kenny Ostrom
Jan 4 at 14:28
|
show 12 more comments
1 Answer
1
active
oldest
votes
There may be other problems, but this line needs to be fixed:
mergeSort(vec, middle + 1, right);
changed to
mergeSort(vec, middle, right);
I would also suggest using the names begin and end instead of left and right, to be consistent with the naming convention used for vector iterators, and because the "right" iterator or index points to the "end" of a vector or array, 1 past the last element of the array.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54039825%2fdivide-and-conquer-merge-sorting-not-working%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
There may be other problems, but this line needs to be fixed:
mergeSort(vec, middle + 1, right);
changed to
mergeSort(vec, middle, right);
I would also suggest using the names begin and end instead of left and right, to be consistent with the naming convention used for vector iterators, and because the "right" iterator or index points to the "end" of a vector or array, 1 past the last element of the array.
add a comment |
There may be other problems, but this line needs to be fixed:
mergeSort(vec, middle + 1, right);
changed to
mergeSort(vec, middle, right);
I would also suggest using the names begin and end instead of left and right, to be consistent with the naming convention used for vector iterators, and because the "right" iterator or index points to the "end" of a vector or array, 1 past the last element of the array.
add a comment |
There may be other problems, but this line needs to be fixed:
mergeSort(vec, middle + 1, right);
changed to
mergeSort(vec, middle, right);
I would also suggest using the names begin and end instead of left and right, to be consistent with the naming convention used for vector iterators, and because the "right" iterator or index points to the "end" of a vector or array, 1 past the last element of the array.
There may be other problems, but this line needs to be fixed:
mergeSort(vec, middle + 1, right);
changed to
mergeSort(vec, middle, right);
I would also suggest using the names begin and end instead of left and right, to be consistent with the naming convention used for vector iterators, and because the "right" iterator or index points to the "end" of a vector or array, 1 past the last element of the array.
edited Jan 4 at 19:18
answered Jan 4 at 16:55
rcgldrrcgldr
16.2k31437
16.2k31437
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54039825%2fdivide-and-conquer-merge-sorting-not-working%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
6
This is a problem that should be solved by debugging. Using your favorite debugger (and/or) IDE, step through the code line by line, each time formulating your expected result of a step before letting the code do it. If the line of code does something else than you expect, investigate there. Debugging like this is a crucial skill to have as a programmer, so use this opportunity!
– Max Langhof
Jan 4 at 13:31
3
Did you run your code using a debugger? Compare your code with the implementation here. What is the difference? Also, claiming that a function is working, thus you won't post the function many times ends up wasting a lot of time if the function that isn't posted is the faulty function.
– PaulMcKenzie
Jan 4 at 13:31
5
@Repikas If i weren't 100% sure that directInsertion is working i would have post it -- If I had a dollar for every post where the unposted "working code" was the actual problem, I would be a rich man. Please post a Minimal, Complete, and Verifiable example.
– PaulMcKenzie
Jan 4 at 13:46
3
I fixed the missing includes, missing print functions, and reordered the functions so it would run. Your example should run without my having to do that. I got a vector index out of range. I'm not saying where because you should get the same when you debug it, and that will be a lot more useful to you.
– Kenny Ostrom
Jan 4 at 14:19
3
also avoid name conflicts. "vector" isn't a wise choice for a variable name. But nice test case -- I would recommend you make it as small as you can and still get the error, so it will be easy to debug.
– Kenny Ostrom
Jan 4 at 14:28