i am trying to solve a kind of weird QuickSort. I partition the array and I create 2 other arrays: the left array and the right array (without the pivot) and I partition them and so on. My code is this:
#include <bits/stdc++.h>
using namespace std;
int partition(vector<int>& ar) {
int pivot=ar[0];
int store=0;
for(int i=0;i<ar.size();i++)
{
if(ar[i]<pivot)
{
store++;
int temp=ar[store];
ar[store]=ar[i];
ar[i]=temp;
}
}
for(int i=0;i<store;i++){
int temp=ar[i];
ar[i]=ar[i+1];
ar[i+1]=temp;
}
for(int i=ar.size()-2;i>store;i--){
int temp=ar[i+1];
ar[i+1]=ar[i];
ar[i]=temp;
}
return store; }
void quickSort(vector <int>& arr) {
if(arr.size()<=1)
{
return;
}
int a=partition(arr);
vector <int> vec1(a);
int b=arr.size()-a-1;
vector <int> vec2(b);
for(int i=0;i<a;i++)
{
vec1[i]=arr[i];
}
for(int i=a+1;i<arr.size();i++)
{
vec2[i]=arr[i];
}
if(vec1.size()<2 && vec2.size()<2)
{
for(int i=0;i<arr.size();i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return;
}
else{
quickSort(vec1);
quickSort(vec2);
}
}
int main() {
int n;
cin >> n;
vector <int> arr(n);
for(int i = 0; i < (int)n; ++i) {
cin >> arr[i];
}
quickSort(arr);
for(int i =0; i <arr.size(); i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
The code is not finished at all, however, here, It should run whereas it does not. I have this error:
Abort Called
Error (stderr):
solution: malloc.c:2372: sysmalloc: Assertion (old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.`
I think it is because I am calling recursively the function quickSort which takes the reference of vector vec1 and vector vec2 and then I create in the function again vector vec1 and vec2...But i am not sure at all!!
Sorry again for such a long question but it is not easy to write it...
Thanks in advance for your answers!!!!