for my bucket sort, I don't know why the out put is segmentation fault: 11 when I try to print out sorted distance. It should be running well on win pc, but I try running it on mac, but i just get error. where am I wrong?
using namespace std;
void bucketSort(vector<double> &arr, int n)
{
vector<double> distance;
vector<double> b[n];
for (int i=1; i<=n/2; i++)
{
double c = sqrt(i)/sqrt(n/2);
cout<<c<<endl;
}
for (int i=0; i<n; i++)
{
double dist = sqrt(pow((arr[i]-0), 2) + pow((arr[i+1]-0), 2));
i = i+1;
distance.push_back(dist);
}
for (int i=0; i<n; i++)
{
int bi = n*distance[i]; // Index in bucket
b[bi].push_back(distance[i]);
}
for (int i=0; i<n; i++)
{
sort(b[i].begin(), b[i].end());
}
int index = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < b[i].size(); j++)
{
distance[index++] = b[i][j];
}
}
for (int i = 0; i < n/2; i++)
{
cout<<distance[i]<<endl;
}
}
int main()
{
vector<double> A;
double numbers;
while (cin>>numbers)
{
A.push_back(numbers);
}
int n = A.size();
bucketSort(A, n);
}
Here is the out put:
Claudes-MBP:desktop BengDai$ ./a.out < n.txt
0.5
0.707107
0.866025
1
Segmentation fault: 11
Claudes-MBP:desktop BengDai$
In your code you use arr[i+1]
in a loop where is in the range 0 to n-1.
This means you will try and use arr[n] which is beyond the end of the array.
This block is also suspect:
for (int i=0; i<n; i++)
{
int bi = n*distance[i]; // Index in bucket
b[bi].push_back(distance[i]);
}
b[bi]
: The value of bi could be bigger than the array size of b and probably is?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.