求助大家一个简单的数组排序算法!!谢谢!
要求对数组里面的元素,统计出现的次数,然后按自小到大的顺序输出;
比如:3 -1 3 2 2
输出:
数字 次数
-1 1
2 2
3 2
谢谢大家指点,我能统计次数,但是不能顺序输出,并且输出数组的元素还是重复的,不合要求!
问题点数:20、回复次数:7Top
1 楼zhangfjj(小张)回复于 2004-12-01 22:58:50 得分 0
冒泡呀、选择呀,多的是Top
2 楼notdefined(未定义)回复于 2004-12-01 23:09:47 得分 0
桶排序,顺手就统计了出现次数了Top
3 楼daidodo(火箭发射机)回复于 2004-12-02 12:40:04 得分 0
如果元素值范围比较小,考虑用数组统计,快而且容易。Top
4 楼kv4000(ABCD(A Brave Csharp Developer))回复于 2004-12-06 09:46:20 得分 15
#include<iostream>
#include<ctime>
using namespace std;
void fill_array(int a[],int max,int &length);
void statistic(int a[],int length );
void swap(int &x,int &y);
int main()
{
const int max=5;
double start,end;
int arr[max],length;
start=static_cast<double>(clock());
fill_array(arr,max,length);
statistic(arr,length );
end=static_cast<double>(clock());
cout<<endl;
cout<<"本程序所用时间是:"<<(end-start)/CLK_TCK<<endl;
return 0;
}
void fill_array(int a[],int max,int &length)
{
int next,index=0;
cout<<"请输入"<<max<<"个数字,以-1结束!\n";
cin>>next;
while((next!=-1)&&(index<max))
{
a[index]=next;
index++;
cin>>next;
}
length=index;
}
void statistic(int a[],int length )
{
int temp,index=1;
bool noappear=true;
cout<<"数组中的内容 : 出现的次数"<<endl;
for(int i=0;i<length-1;i++)
{
for(int j=i+1;j<length;j++)
if ((a[i]<a[j]))
swap(a[i],a[j]);
}
for(int i=0;i<length;i++)
{
if(a[i]==a[i+1])
index++;
else
if (index==1)
{
cout<<a[i]<<" ";
cout<<"1次"<<endl;
}
else
{
cout<<a[i]<<" ";
cout<<index<<"次"<<endl;
index=1;
}
}
}
void swap(int &x,int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}Top
5 楼pcboyxhy(-273.15℃)回复于 2004-12-06 10:11:01 得分 5
#include<algorithm>
#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;
int main()
{
vector<int>v;
int input;
for( ; cin>>input; )
{
if(input==-999)
break;
v.push_back(input);
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
cout<<i<<":"<<v[i]<<endl;
system("PAUSE");
}
Top
6 楼pcboyxhy(-273.15℃)回复于 2004-12-06 10:12:11 得分 0
统计数据可以用hash表Top
7 楼xuzheng318(忧郁王子)回复于 2004-12-06 10:19:53 得分 0
HASH表确实能解决你的问题,下面的Sample是SGI版的STL中的例子:
void lookup(const hash_set<const char*, hash<const char*>, eqstr>& Set,
const char* word)
{
hash_set<const char*, hash<const char*>, eqstr>::const_iterator it
= Set.find(word);
cout << word << ": "
<< (it != Set.end() ? "present" : "not present")
<< endl;
}
但是hash_set这个类属于STL的扩展, 其它版本的STL(如VC中带的)不一定有此类. 建议你用SGI的STL.
Top




