The quicksort function works perfectly fine as ive tried it with the standard array. When using vectors however, I get an error message saying swap function doesnt take 3 arguments. Any help would be appreciated.
void quicksort(vector<int> &vec, int L, int R) {
int i, j, mid, piv;
i = L;
j = R;
mid = L + (R - L) / 2;
piv = vec[mid];
while (i<R || j>L) {
while (vec[i] < piv)
i++;
while (vec[j] > piv)
j--;
if (i <= j) {
swap(vec, i, j); //error=swap function doesnt take 3 arguments
i++;
j--;
}
else {
if (i < R)
quicksort(vec, i, R);
if (j > L)
quicksort(vec, L, j);
return;
}
}
}
void swap(vector<int> v, int x, int y) {
int temp = v[x];
v[x] = v[y];
v[y] = temp;
}
int main() {
vector<int> vec1;
const int count = 10;
for (int i = 0; i < count; i++) {
vec1.push_back(1 + rand() % 100);
}
quicksort(vec1, 0, count - 1);
}
See
void quicksort(vector<int> &vec, int L, int R)
and
void swap(vector<int> v, int x, int y)
The first parameter does not use reference.
Like various comment say, problem is that your version of swap is being confused with std::swap. You can fix it by either moving the implementation of swap before you use it or add a declaration before you use it.
Also per Devin's answer, pass by reference so you get the swapped values back.
Here is the fixed code:
#include <vector>
using namespace std;
void swap(vector<int>& v, int x, int y);
void quicksort(vector<int> &vec, int L, int R) {
int i, j, mid, piv;
i = L;
j = R;
mid = L + (R - L) / 2;
piv = vec[mid];
while (i<R || j>L) {
while (vec[i] < piv)
i++;
while (vec[j] > piv)
j--;
if (i <= j) {
swap(vec, i, j); //error=swap function doesnt take 3 arguments
i++;
j--;
}
else {
if (i < R)
quicksort(vec, i, R);
if (j > L)
quicksort(vec, L, j);
return;
}
}
}
void swap(vector<int>& v, int x, int y) {
int temp = v[x];
v[x] = v[y];
v[y] = temp;
}
int main() {
vector<int> vec1;
const int count = 10;
for (int i = 0; i < count; i++) {
vec1.push_back(1 + rand() % 100);
}
quicksort(vec1, 0, count - 1);
}
Related
I tried to implement merge sort using C++, however, something went wrong. I have no idea what is wrong.
The following code is what I wrote based on CLRS. I think it is quite easy to understand the meaning.
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int>& nums, int p, int q, int r);
void mergeSort(vector<int>& nums, int p, int r){
if (p < r) {
int q = (p + r) / 2;
mergeSort(nums, p, q);
mergeSort(nums, q + 1, r);
merge(nums, p, q, r);
}
}
void merge(vector<int>& nums, int p, int q, int r) {
int s1 = p, s2 = q + 1;
vector<int> l1, l2;
for (int i = s1; i <= q; i++) {
l1.push_back(nums[i]);
}
for (int i = s2; i <= r; i++) {
l2.push_back(nums[i]);
}
int left = 0, right = 0;
int idx = 0;
while (left < l1.size() && right < l2.size()) {
if (l1[left] < l2[right]) {
nums[idx] = l1[left++];
}
else {
nums[idx] = l2[right++];
}
idx++;
}
while (left < l1.size()) {
nums[idx++] = l1[left++];
}
while (right < l2.size()) {
nums[idx++] = l2[right++];
}
}
int main() {
vector<int> vect;
vect.push_back(1);
vect.push_back(3);
vect.push_back(12);
vect.push_back(23);
vect.push_back(4);
vect.push_back(11);
vect.push_back(44);
vect.push_back(322);
mergeSort(vect, 0, vect.size() - 1);
for (int i = 0; i < vect.size(); i++) {
cout << vect[i] << endl;
}
return 0;
}
I want to use the program to sort some integers, however, it only shows many duplicate numbers. What's going on? I don't think there is a problem of the merge function.
The code needs a one line fix:
int idx = p; // not idx = 0
Optimized top down using arrays from Wiki article (note bottom up is slightly faster):
void TopDownMerge(int A[], int bgn, int mid, int end, int B[])
{
int i, j, k;
i = bgn, j = mid, k = bgn;
while(1){
if(A[i] <= A[j]){ // if left smaller
B[k++] = A[i++]; // copy left element
if(i < mid) // if not end of left run
continue; // continue
do // else copy rest of right run
B[k++] = A[j++];
while(j < end);
break; // and break
} else { // else right smaller
B[k++] = A[j++]; // copy right element
if(j < end) // if not end of right run
continue; // continue
do // else copy rest of left run
B[k++] = A[i++];
while(i < mid);
break; // and break
}
}
}
void TopDownSplitMerge(int B[], int bgn, int end, int A[])
{
if (end - bgn <= 1) // if run size == 1
return; // consider it sorted
int mid = (end + bgn) / 2;
TopDownSplitMerge(A, bgn, mid, B);
TopDownSplitMerge(A, mid, end, B);
TopDownMerge(B, bgn, mid, end, A);
}
void TopDownMergeSort(int A[], int n) // n = size (not size-1)
{
if(n < 2)
return;
int *B = new int [n]; // 1 time allocate and copy
for(size_t i = 0; i < n; i++)
B[i] = A[i];
TopDownSplitMerge(B, 0, n, A); // sort data from B[] into A[]
delete B;
}
Afterwards, I finally get to fix the bugs of my program. After modification, here is the code:
class Solution {
public:
vector<int> temp;
vector<int> sortArray(vector<int>& nums) {
temp.resize((int)nums.size(), 0);
mergeSort(nums, 0, nums.size() - 1);
return nums;
}
void mergeSort(vector<int>& nums, int start, int end) {
if (start >= end) return;
int middle = (start + end) / 2;
mergeSort(nums, start, middle);
mergeSort(nums, middle + 1, end);
merge(nums, start, middle, end);
}
void merge(vector<int>& nums, int leftStart, int middle, int rightEnd) {
int leftEnd = middle;
int rightStart = middle + 1;
int i = leftStart, j = rightStart;
int index = 0;
while (i <= leftEnd && j <= rightEnd) {
if (nums[i] < nums[j]) {
temp[index] = nums[i++];
}
else {
temp[index] = nums[j++];
}
index++;
}
while (i <= leftEnd) {
temp[index++] = nums[i++];
}
while (j <= rightEnd) {
temp[index++] = nums[j++];
}
for (int i = 0; i < rightEnd - leftStart + 1; i++) {
nums[i + leftStart] = temp[i];
}
}
};
Here is something should be careful next time:
In the merge part, it is difficult to merge in place. It'd be better to use another temp array to store the merged results and update to the target array (nums in this case).
Readable identifers is very recommended (Although the pseudocode of CLRS may not use that part).
Need to use debuggers to find the bug of program {However, it takes like forever to load local variables of VS Code debugers.
VS Code catches this exception when I run my quicksort algorithm:
EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffffc). This happens on the first line in partition():
int i = p;
I have tried to implement the Cormen algorithm: http://www.cs.fsu.edu/~lacher/courses/COP4531/lectures/sorts/slide09.html
Why can I not access the variable p? Is it released, and if so, how do I fix this?
My code
//.h file
void sortVector(vector<int> &vec, int p=0, int r=-2);
int partition(vector<int> &vec, int p, int r);
//.cpp file
int partition(vector<int> &vec, int p, int r) {
int i = p;
for (int j = p; j <r-1; ++j) {
if (vec[j] < vec[r-1]) {
swap(vec[j], vec[r-1]);
i++;
}
swap(vec[i], vec[r-1]);
}
return i;
}
void sortVector(vector<int> &vec, int p, int r) {
if (r == -2) {
r = vec.size();
}
if (p-r<1) {
int q = partition(vec, p, r);
sortVector(vec, p, q);
sortVector(vec, q+1, r);
}
}
I am including "std_lib_facilities.h" from Stroustrup: Programming Principles and Practice Using C++.
You need to write swap(vec[i], vec[r-1]); out of for loop.
It should be like this -
//.cpp file
int partition(vector<int> &vec, int p, int r) {
int i = p;
for (int j = p; j <r-1; ++j) {
if (vec[j] < vec[r-1]) {
swap(vec[j], vec[r-1]);
i++;
}
}
swap(vec[i], vec[r-1]);
return i;
}
There were problems in both functions:
partition():
first swap had wrong arguments.
second swap had to be moved out of
the for-loop (suggested by Faruk Hossain)
if (vec[j] < vec[r-1]) became if (vec[j] <= vec[r-1])
sortVector():
if (p-r<1) became if (p<r)
Working code below.
int partition(vector<int> &vec, int p, int r) {
int i = p;
for (int j = p; j <r-1; ++j) {
if (vec[j] <= vec[r-1]) {
swap(vec[i], vec[j]);
i++;
}
}
swap(vec[i], vec[r-1]);
return i;
}
void sortVector(vector<int> &vec, int p, int r) {
if (r == -2) {
r = vec.size();
}
if (r>p) {
int q = partition(vec, p, r);
sortVector(vec, p, q);
sortVector(vec, q+1, r);
}
}
I have written parallel implementation of merge sort but for some reasons that I cannot understand sometimes it finishes properly, and sometimes it crashes. Whats more interesting following code sometimes seems to crash AFTER it has sorted the array (the array gets printed and then code stops working).
Could anyone help me diagnose a problem? I guess I messed something with threads and they are not ending properly?
void printArray (int* a, int elements) {
for(int i = 0; i < elements; i++) {
printf("%d\t", a[i]);
}
}
void merge2(int a[], int l, int middle, int r) {
int leftIterator = l;
int rightIterator = middle+1;
int k = 0;
int* tmp = new int[(r - l)];
while (leftIterator <= middle && rightIterator <= r) {
if (a[leftIterator] < a[rightIterator]) {
tmp[k] = a[leftIterator];
leftIterator++;
}
else {
tmp[k] = a[rightIterator];
rightIterator++;
}
k++;
}
if (leftIterator <= middle) {
while (leftIterator <= middle) {
tmp[k] = a[leftIterator];
leftIterator++;
k++;
}
}
else {
while (rightIterator <= r) {
tmp[k] = a[rightIterator];
rightIterator++;
k++;
}
}
for (int i = 0; i <= (r - l); i++)
a[l + i] = tmp[i];
}
void merge_sort(int a[], int l, int r) {
if (l != r) {
int middle= (l + r) / 2; //find middle element
#pragma omp parallel sections
{
#pragma omp section
merge_sort(a, l, middle);
#pragma omp section
merge_sort(a, middle + 1, r);
}
merge2(a, l, middle, r);
}
}
int main(void) {
int elements = 10;
int a[10] = { 10,2,1,5,6,3,4,9,8,7 };
merge_sort(a, 0, elements-1);
printArray(a, elements); // print sorted array
printf("\n");
return 0;
}
I don't understand why they give me different output when I compile them. For example ... when I compile only one algorithm the answer is good, the same is for the other one, but when I compile them both at the same time they give me some weird output.
My code:
#include <iostream>
using namespace std;
int parent(int i){
return i/2;
}
int leftChild(int i){
return 2*i+1;
}
int rightChild(int i){
return 2*i+2;
}
void maxHeapify(int a[], int i, int n){
int largest;
int temp;
int l = leftChild(i);
int r = rightChild(i);
// p.countOperation("CMPbottomUp",n);
if (l <= n && (a[l] > a[i]))
largest = l;
else
largest = i;
// p.countOperation("CMPbottomUp",n);
if (r <= n && (a[r] > a[largest]))
largest = r;
if (largest != i){
// p.countOperation("ATTbottomUp",n);
temp = a[i];
// p.countOperation("ATTbottomUp",n);
a[i] = a[largest];
//p.countOperation("ATTbottomUp",n);
a[largest] = temp;
maxHeapify(a, largest, n);
}
}
void buildMaxHeap(int a[], int n){
for (int i=n/2; i>=0; i--){
maxHeapify(a, i, n);
}
}
void heapSort(int a[],int n){
buildMaxHeap(a,n);
int n1=n;
int temp;
for(int i=n1;i>0;i--){
temp = a[0];
a[0] = a[i];
a[i] = temp;
n1--;
maxHeapify(a,0,n1);
}
}
int partitionArray(int arr[], int left, int right){
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}
void quickSort(int arr[], int left, int right) {
int index;
index = partitionArray(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}
int main(){
int x[8]= {5,87,21,4,12,7,44,3};
int a[8];
for(int i=0;i<8;i++){
a[i] = x[i];
}
heapSort(x,8);
quickSort(a,0,8);
for(int i=0;i<8;i++){
cout<<a[i]<<' ';
}
cout<<endl;
for(int j=0;j<8;j++){
cout<<x[j]<<' ';
}
return 0;
}
Example output:
1) When I compile only one algorithm the output is : 3,4,5,7,12,21,44,87 (which is good)
2) When I compile both of them in the code the output is: 87,4,5,7,12,21,44,87 (quickSort) and 3,3,4,5,7,12,21,44 (heapSort)
I think that should work:
heapSort(x,7);
quickSort(a,0,7);
Arrays a and x are right next to each others in stack. Seeing how you have duplicate value 87 in output, it seems your sort functions access memory outside the array you give to them. This is buffer overrun, a type of Undefined Behaviour. With that, your code could do anything because you have corrupted variable values (or worse, corrupted addresses/pointers).
Double check how you access arrays. Remember that C array indexes for your arrays of length 8 are 0..7!
Here is some working code that implements a modified version of the Quicksort algorithm that uses Insertion Sort for array size n > 8. My test array isn't sorting exactly right, and I think it must be with my implementation of Insertionsort and Insert.
The general form of the recursive Insertionsort algorithm is:
void Insertionsort(int S[], int n)
{
if(n>1)
Insertionsort(S,n-1);
Insert(S,n-1);
}
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>=0 && S[j] > key)
{
S[j+1] = S[j];
j--;
}
S[j+1] = key;
}
Here is my complete working code that does not sort quite exactly right:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int comparisons = 0;
int compare_qs_m3_ins[12];
// Function prototypes
int partition(int *S,int l, int u);
void exchange(int list[], int p, int q);
void Insert(int S[], int k);
void Insertionsort(int S[], int low, int hi);
void Quicksort_Insert_M3(int S[], int n, int p, int r);
int main()
{
srand (time(NULL));
// Declare all arrays used for testing
int S1_500[500];
int S2_500[500];
int S3_500[500];
int S1_300[300];
int S2_300[300];
int S3_300[300];
int S1_100[100];
int S2_100[100];
int S3_100[100];
int S1_8[8];
int S2_8[8];
int S3_8[8];
// Fill arrays with random integers
for(int i=0; i<500; i++)
{
S1_500[i] = rand()%1000;
S2_500[i] = rand()%1000;
S3_500[i] = rand()%1000;
}
for(int i=0; i<300; i++)
{
S1_300[i] = rand()%1000;
S2_300[i] = rand()%1000;
S3_300[i] = rand()%1000;
}
for(int i=0; i<100; i++)
{
S1_100[i] = rand()%500;
S2_100[i] = rand()%500;
S3_100[i] = rand()%500;
}
for(int i=0; i<8; i++)
{
S1_8[i] = rand()%100;
S2_8[i] = rand()%100;
S3_8[i] = rand()%100;
}
Quicksort_Insert_M3(S1_500,500,0,499);
compare_qs_m3_ins[0] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_500,500,0,499);
compare_qs_m3_ins[1] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_500,500,0,499);
compare_qs_m3_ins[2] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_300,300,0,299);
compare_qs_m3_ins[3] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_300,300,0,299);
compare_qs_m3_ins[4] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_300,300,0,299);
compare_qs_m3_ins[5] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_100,100,0,99);
compare_qs_m3_ins[6] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_100,100,0,99);
compare_qs_m3_ins[7] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_100,100,0,99);
compare_qs_m3_ins[8] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_8,8,0,7);
compare_qs_m3_ins[9] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_8,8,0,7);
compare_qs_m3_ins[10] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_8,8,0,7);
compare_qs_m3_ins[11] = comparisons;
comparisons = 0;
//for(int i=0; i<12; i++)
//cout << compare_qs_m3_ins[i] << endl;
for(int i=0;i<499;i++)
cout << S1_500[i] << endl;
}
int partition(int *S,int l, int u)
{
int x = S[l];
int j = l;
for(int i=l+1; i<=u; i++)
{
comparisons++;
if(S[i] < x)
{
j++;
swap(S[i],S[j]);
}
}
int p = j;
swap(S[l],S[p]);
return p;
}
void swap(int &val1, int &val2)
{
int temp = val1;
val1 = val2;
val2 = temp;
}
void exchange(int list[], int p, int q)
{
int temp = list[p];
list[p] = list[q];
list[q] = temp;
}
int Sort3(int list[], int p, int r)
{
int median = (p + r) / 2;
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
}
else
{
exchange(list,median,r);
}
}
else
;
}
else
{
comparisons++;
if(list[p] > list[r])
{
comparisons++;
if(list[median] < list[r])
{
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
}
else
{
exchange(list,p,r);
}
}
else
{
exchange(list,p,median);
}
}
return list[r];
}
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>=0 && S[j] > key)
{
S[j+1] = S[j];
j--;
comparisons++;
}
comparisons++;
S[j+1] = key;
}
void Insertionsort(int S[], int low, int hi)
{
if((hi-low)+1>1)
Insertionsort(S,low+1,hi);
Insert(S,hi-low);
}
void Quicksort_Insert_M3(int S[], int n, int low, int hi)
{
if((hi-low)<=8)
Insertionsort(S,low,hi);
else
{
if(low < hi)
{
if((low+1) == hi)
{
comparisons++;
if(S[low] > S[hi])
swap(S[low],S[hi]);
}
else
{
Sort3(S,low,hi);
if((low+2)<hi)
{
swap(S[low+1],S[(low+hi)/2]);
int q = partition(S, low+1, hi-1);
Quicksort_Insert_M3(S, n, low, q-1);
Quicksort_Insert_M3(S, n, q+1, hi);
}
}
}
}
}
The function supposed to sort three array elements in ascending order doesn't:
int Sort3(int list[], int p, int r)
{
called only for p + 2 <= r, so
int median = (p + r) / 2;
p < median < r here. Let a = list[p], b = list[median] and c = list[r].
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
So here we have a <= b, c < b and a < c, together a < c < b
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
but you place them in order c, a, b. Probably you intended to use if (list[r] < list[p]) there.
}
else
c <= a <= b
{
exchange(list,median,r);
so that arranges them in order a, c, b.
}
}
else
;
}
else
Here, b < a.
{
comparisons++;
if(list[p] > list[r])
{
c < a
comparisons++;
if(list[median] < list[r])
{
Then b < c < a
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
Yup, that's correct.
}
else
c <= b < a
{
exchange(list,p,r);
}
Okedoke.
}
else
{
b < a <= c
exchange(list,p,median);
Okay.
}
}
return list[r];
}
Why does this function return anything? You don't use the return value anyway.
"The general form of the recursive Insertionsort algorithm is" - if you need to have a head-recursive algorithm, yes, otherwise a better version is:
void Insertionsort(int S[], int i, int n)
{
Insert(S, i, n);
if(i < n)
Insertionsort(S, i+1, n);
}
which is much more understandable. Also, you might as well have put the body of Insert into Insertionsort.
I'm not going to try and figure out your overly complicated version of quicksort. A decent quicksort is around 20 lines or less (like this - www.algolist.net/Algorithms/Sorting/Quicksort) (and add another 10 or less for insertion sort). I suggest getting a better understanding by looking at another implementation and rewriting yours.
I believe this could've been asked as an extension of your previous question.