I am trying to implement quicksort using C++ containers and iterators.
I am new to C++ STL.
I am getting a seg fault. For all my C programs I always used valgrind to figure out situations like this but right now its not helping. Any tips/suggestions/solutions will be appreciated.
#include <iostream> #include <fstream> #include <vector> #include <iterator> #include <algorithm> using namespace std; void print(vector<int> A){ for(vector<int>::iterator i = A.begin(); i != A.end(); i++) cout << *i << " "; cout<<endl; } vector<int>::iterator Partition(vector<int>::iterator l, vector<int>::iterator r){ int x = *l; vector<int>::iterator i = l + 1; for(vector<int>::iterator j = l + 1; j <= r; j++){ if(*j < x){ iter_swap(j, i); i++; } } iter_swap(l, (i - 1)); return i - 1; } void QuickSort(vector<int>::iterator l, vector<int>::iterator r){ if (distance(l, r) <= 1) return; vector<int>::iterator p = Partition(l, r); QuickSort(l, p - 1); QuickSort(l + distance(l, p), r); } int main(int argc, const char * argv[]){ if (argc != 2){ cout << "Usage: ./Sort <file_name>" << endl; //<file_name> refers to a file of integers where each line contains a number return EXIT_FAILURE; } ifstream infile(argv[1]); vector<int> A; int num; while(infile >> num){ A.push_back(num); } //print(numbers); int n = 0; print(A); QuickSort(A.begin(), A.end()); print(A); //cout << n << endl; return EXIT_SUCCESS; }
Aucun commentaire:
Enregistrer un commentaire