求助 string 转换成数组并快速排序

boy3320 2007-11-19 10:57:50
大致代码如下.(出错,调试了几天,未果.盼达人指导)
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
void quicksort(int[],int left,int right)
{int i,j,temp;
i=left;
j=right;
temp=a[left];
if(left>right)
return;
while(i!=j)
{while(a[j]>=temp&&j>i)
j--;
if(j>i)
a[i++]=a[j];
while(a[i]<=temp&&j>i)
i++;
if(j>i)
a[j--]=a[i];
}
a[i]=temp;
quicksort(a,left,i-1);
quicksort(a,i+1,right);
}
int main()
{
int i,a[7];
ifstream in("num.txt");
for(string str;getline(in,str);)
istringstream tmp(str);
while(tmp>>a[i++])

quickSort(a,0,6);
/*排好序的结果*/
for(i=0;i<7;i++)
printf("%4d\n",a[i]);

}
...全文
93 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
boy3320 2007-11-19
  • 打赏
  • 举报
回复
补充: num.txt中的内容:

20 33 59 86 78 75 101 255
effective_person 2007-11-19
  • 打赏
  • 举报
回复
思路不变只是你写的时候有写问题

呵呵你给我8个数程序确是 7害的我调试了好久
呵呵
^_^
effective_person 2007-11-19
  • 打赏
  • 举报
回复
思路不变只是写的时候有写问题
请牢记 使用变量是要初始化,否则将会导致不明确的行为
effective_person 2007-11-19
  • 打赏
  • 举报
回复
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>//头文件
using namespace std;
void quicksort(int a[],int left,int right)
{int i,j,temp;
i=left;
j=right;
temp=a[left];
if(left> right)
return;
while(i!=j)
{while(a[j]>=temp&&j> i)
j--;
if(j> i)
a[i++]=a[j];
while(a[i] <=temp&&j> i)
i++;
if(j> i)
a[j--]=a[i];
}
a[i]=temp;
quicksort(a,left,i-1);
quicksort(a,i+1,right);
}
int main()
{
int i=0,a[8]; //i初始化
string strl="";
string str;
ifstream in( "num.txt");
while(getline(in,str))
{
strl+=str;
}
cout<<strl<<endl;
istringstream tmp(strl.c_str());
while(tmp>>a[i++])//转化成int
{}
for(i=0;i <8;i++)
printf( "%4d ",a[i]);
printf("\n");
quicksort(a,0,6);
for(i=0;i <8;i++) //8
printf( "%4d\n ",a[i]);
}

你的程序毛病不小啊
bargio_susie 2007-11-19
  • 打赏
  • 举报
回复
把你主函数里改了下,自己看看。。

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

void quickSort(int a[], int left, int right)
{
int i,j,temp;
i = left;
j = right;
temp = a[left];
if (left > right)
return;

while (i != j)
{
while(a[j] >= temp && j > i)
j--;
if(j > i)
a[i++] = a[j];
while(a[i] <= temp && j > i)
i++;
if(j > i)
a[j--] = a[i];
}
a[i] = temp;

quickSort(a, left, i-1);
quickSort(a, i+1, right);
}

int main()
{
int i=0, a[20];
string str, tmp;
string::size_type index = 0, index_temp;
ifstream in( "num.txt");

while (getline(in, str))
{
while (index < str.size())
{
index_temp = str.find_first_of(' ', index);
if (index_temp == string::npos)
{
tmp = str.substr(index);
a[i++] = atoi(tmp.c_str());
break;
}
tmp = str.substr(index, index_temp-index);
a[i++] = atoi(tmp.c_str());
index = str.find_first_not_of(' ', index_temp);
}

quickSort(a, 0, i-1);
/*排好序的结果*/
for(int j=0; j<i; j++)
cout << a[j] << ' ';
cout << endl;
}

return 0;
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧