我已经尝试了几个小时才能让它工作,但无论出于何种原因,我都无法正确打印我的数组。这是我的代码(下面的 .txt 文件)
//
// main.cpp
// cs498 -mp1
#include<iostream>
#include<stdlib.h>
#include <fstream>
#include<time.h>
int sortsize=1000;
int seed=1;
using namespace std;
void readfile(int *input, int size)
{
}
void writefile(int *input, int size)
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Radix Sort\n";
for(int i=0; i<size; i++)
myfile << input[i] << endl;
myfile.close();
}
void radixsort(int *a, int arraySize)
{
int i, bucket[sortsize], maxVal = 0, digitPosition =1 ;
for(i = 0; i < arraySize; i++) {
if(a[i] > maxVal) maxVal = a[i];
}
int pass = 1;
while(maxVal/digitPosition > 0) {
// reset counter
int digitCount[10] = {0};
// count pos-th digits (keys)
for(i = 0; i < arraySize; i++)
digitCount[a[i]/digitPosition%10]++;
// accumulated count
for(i = 1; i < 10; i++)
digitCount[i] += digitCount[i-1];
// To keep the order, start from back side
for(i = arraySize - 1; i >= 0; i--)
bucket[--digitCount[a[i]/digitPosition%10]] = a[i];
for(i = 0; i < arraySize; i++)
a[i] = bucket[i];
cout << "pass #" << pass++ << ": ";
digitPosition *= 10;
}
}
void ccradixsort(int *array /* you will need more arguments */)
{
}
int main(int argc, char *argv[])
{
clock_t start, end;
int *sortarray;
int *input;
if(argc > 1)
sortsize = atoi(argv[1]);
sortarray = (int *) malloc(sortsize * sizeof(int));
input = (int *) malloc(sortsize * sizeof(int));
if(/*argc == 3*/ true)
{
seed = atoi(argv[2]);
for(int i = 0; i < sortsize; i++)
{
input[i] = rand();
}
}
else
{
readfile(input,sortsize);
}
for(int i = 0; i < sortsize; i++)
{
sortarray[i] = input[i];
}
start = clock();
radixsort(sortarray, sizeof(sortarray));
end = clock();
cout << "Sorted in " << (double)(end - start)/CLOCKS_PER_SEC << " seconds by radixsort()" << endl;
writefile(sortarray, sortsize);
/*
for(int i = 0; i < sortsize; i++)
{
sortarray[i] = input[i];
}
start = clock();
ccradixsort(sortarray);
end = clock();
cout << "Sorted in " << (double)(end - start)/CLOCKS_PER_SEC << " seconds by ccradixsort()" << endl;
//if(argc != 3)
// writefile(sortarray, sortsize);
*/
}
这是它生成的文本文件的一部分:
>Radix Sort
>16807
>101027544
>282475249
>470211272
>984943658
>1144108930
>1457850878
>1622650073
>1458777923
>2007237709
>823564440
>1115438165