【发布时间】:2020-06-14 15:08:59
【问题描述】:
整个程序正确执行后,我在终端收到 munmap_chunk(): invalid pointer 和 Aborted (core dumped) 消息。
基数排序功能:
我按以下步骤设计了该功能:
- 查找最大值并计算编号。其中的位数。
- 运行“d”或否的主循环。位数次。
- 数组 C 中的每次频率都计入第 i 个元素。
for(int i = 0 ;i < A.size(); i++){
int t = (int(A[i]/pow(10,j))%10);
++C[t];
}
- 然后是计数排序
- 用 B 更新 A 的值。
#include<bits/stdc++.h>
using namespace std;
void Print(vector<int> &A){
for(auto i =A.begin(); i!= A.end(); i++){
cout << *i << " ";
}
cout << endl;
}
void radixSort(vector<int> &A){
int k = A[0];
for(auto i = A.begin(); i!=A.end(); i++){
if(*i > k) k =*i;
}
int d =0;
while(k >0){
k = k/10;
d++;
}
vector<int> result;
for(int j =0; j <d; j++)
{
vector<int> C(10, 0); // Making the array Count of k elements with all 0's
vector<int> B(A.size()); // Output Array
for(int i = 0 ;i < A.size(); i++){
int t = (int(A[i]/pow(10,j))%10); // for taking ith value
++C[t]; // Counting Frequencies of elements in Input array
}
for(int i=1; i<= C.size(); i++){ // Calculating no of elements occuring before postion i
C[i]+= C[i-1]; // Or Calculating final postion of the value
}
for(int i = B.size()-1;i >= 0; i--){
int t = (int(A[i]/pow(10,j))%10);
B[C[t]-1] = A[i]; // Placing the elemsnts from Input Array in Output array accoring to their position
--C[t]; // Decrementing so as to place a same value on left side ( if it Exits)
}
result = A = B;
}
}
主要功能
int main(){
vector<int> A;
srand(time(NULL));
for(int i =0; i< 10; i++){
A.push_back(rand()%1000);
}
cout << "Input Array : " << endl;;
Print(A);
radixSort(A);
cout << "Output Sorted Array : " << endl;;
Print(A);
return 0;
}
【问题讨论】:
-
在处理整数基数和指数时不要使用
pow。pow函数是一个可能不准确的浮点函数。
标签: c++ sorting segmentation-fault coredump radix-sort