So, I have a function that reads strings from a file and pushes them into a vector of strings called words. I have a Quicksort function which essentially would sort the whole vector, but when I call the Quicksort function, it gives me this error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)" and in the Virtual Box, I am using Debian 9, it gives me a Segmentation Error.
int main()
{
int time[5];
vector<string> words;
words=ReadFromFile();
auto start = std::chrono::system_clock::now();
quicksort(words, 0, words.size()-1);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end-start;
cout<<endl;
time[2]=elapsed_seconds.count();
cout<<" Elapsed time: " << elapsed_seconds.count() <<"\n ";
cout<<endl;
}
I want to get the time that it takes the function to sort all the words.
void quicksort(vector<string> words, long int from, long int to) //goes into infinite loop
{
if (from > to)
{
return;
}
long int p = partition(words, from, to);
quicksort(words, from, p);
quicksort(words, p + 1, to);
}
long int partition(vector<string> words, long int from, long int to)
{
string pivot = words[from];
long int i = from - 1;
long int j = to + 1;
while (i < j)
{
i++;while (words[i] > pivot){i++;}
j--;while (words[j] < pivot){j--;}
if (i < j){std::swap(words[i],words[j]);}
}
return j;
}
My read from file function is this-
vector<string> ReadFromFile(){
vector<string> words;
ifstream read;
read.open("macbeth.txt");
if(!read.is_open())
{
cout<<"Error Opening file"<<endl;
}
else
{
while(!read.eof())
{
string line;
getline(read,line);
stringstream Curstr(line);
while(Curstr>>line)
{
words.push_back(line);
}
}
read.close();
}
return words;
}
So I get a EXE_bad_access, and the recursion runs for about 50,000 times.
@EDIT
Using the debugger, I found out that pivot
is not getting the value from words[from]
. It shows that string pivot = ""
instead it should have the value like string pivot = words[from] //MACBETH
which is the value of words[from]
where from = 0
when the function is called the first time. Now, how do I get the value into pivot so it can divide the vector and perform the sort.