首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

帮小弟我看看一个排序有关问题

2012-03-07 
帮我看看一个排序问题我用G++编译能通过但是运行程序出现错误,好象是数组益处,我主要是想实现从TXT文件中

帮我看看一个排序问题
我用G++编译能通过但是运行程序出现错误,好象是数组益处,我主要是想实现从TXT文件中读取整数并从小到大排序.文件格式如下(其中整数个数和数本身都是随机的,每个整数用 ", "分隔):
1,9,2,-10,0,-4
输出要求是:
-10,-4,0,1,2,9
#include   <iostream>
#incldue   <string>
#include   <fstream>

using   namespace   std;

const   int   INTEGER_NUMBER   =10;
const   int   STRING_LENGHT   =127;
const   int   SINGLE_NUMBER_LENGHT=10;

void   QuickSort(int   R[],int   low,int   high);
int   Partition(int   R[],int   low   ,int   high);

int   Partition(int   R[],int   i,int   j)
{
        int   pivot   =   R[i];
        while(i <j)
        {
                while(i   <   j&&R[j]> =pivot)
                {
                        j--;
                }
                if(i   <   j)
                {
                        R[i++]=R[j];
                }
                while(i   <   j   &&   R[i]   <=pivot)
                {
                        i++;
                }
                if(i   <   j)
                {
                        R[j--]   =   R[i];
                }
        }
        R[i]   =   pivot;
        return   i;
}

void   QuickSort(int   R[],int   low,int   high)
{
        int   pivotpos;
        int   nCount   =   0;
        nCount++;
        if(nCount   ==   1   ||   nCount   ==   3   ||   nCount   ==4)
      {
                for(int   i   =0;i <INTEGER_NUMBER;i++)
              {
                        cout   < <   R[i]   < <   " ";
                        cout   < <   endl;  
              }
      }
        if(low   <   high)
      {
              pivotpos   =   Partition(R,low,high);
              QuickSort(R,low,pivotpos-   1);
              QuickSort(R,pivotpos+1,high);


        }
}

int   main(void)
{
        ifstream   infile;
        int   nTempValue   =   0;
        int   nStringLenght   =   0;
        int   nIntegerNumber[INTEGER_NUMBER];
        char   cString[STRING_LENGHT];
        char   cTempChar[SINGLE_NUMBER_LENGHT];
        string   strMyString   =   " ";
        string   strTempString   =   " ";

        infile.open( "myfile01.txt ",ios::in);
        if(!infile)
        {
                  return   0;        
        }
        while(!infile.eof())
      {
                infile.getline*(cString,127);
                strMyString   =   cString;
                nStringLenght   =   strMyString.length();
                for(int   i   =   0;i <nStringLenght;i++)
                {
                        //这部分有问题似乎只取出了一个整数
                        int   nCommaPos   =   strMyString.find   ( ", ");
                        memset(cTempChar, '\0 ',10);
                        strTempString   =   strncpy(cTempChar,strMyString.c_str(),nCommaPos);
                        nTempValue   =   atoi(cTempChar);
                        nIntegerNumber[i]   =   nTempValue;
              }    
        }
        infile.close();
        QuickSort(nIntegerNumber,0,INTEGER_NUMBER-1);
        return   0;
}


[解决办法]
给你几个排序的例子作参考
#include <iostream>
#include <cstdio>
#include <ctime>
using namespace std;

const int TOTAL_NUMBER = 50000;

//***************************************************
//-------------------快速排序算法---------------------
//***************************************************
//将数组分离成左右两部分
template <typename T>
int Partition(T *pA, int p, int r)
{
int i = p;
int j = r;
T x =pA[p];
while(1)
{
while(pA[j] > x) //从右边取出小于等于x的值的索引
j = j - 1;
while(pA[i] <= x)
i = i + 1; //从左边取出大于x的值的索引

if(i < j)
{ //交换使元素分组
std::swap <T> (pA[i], pA[j]);
}
else
{
if(p != j); //考虑最坏情况
std::swap <T> (pA[p], pA[j]);
return j;
}
}

}



//递归调用实现快速排序函数
template <typename T>
void QuickSort(T * pA, int p, int r)
{
if(p < r)
{
int q;
q = Partition(pA, p, r);
QuickSort(pA, p, q-1);
QuickSort(pA, q+1, r);
}
}
//---------------------------------------------------


//=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
//归并排序算法
//=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
//将两个数组a[], b[]合并为一个数组c[]
void mergeAB(int c[], int cl,
int a[], int al, int ar,
int b[], int bl, int br )
{
int i = al, j = bl;

for (int k = cl; k < cl+ar-al+br-bl+1; ++k)
{
if (i > ar){c[k] = b[j++]; continue;}
if (j > br){c[k] = a[i++]; continue;}
c[k] = ( a[i] < b[j] ) ? a[i++]: b[j++];
}
}

//两路归并排序
template <typename T>
void merage(T * a, int al, int am, int ar)
{
T * b = new T[ar - al +1];
int i = al, j = am + 1;

for(int k=0; k < ar - al + 1; ++k)
{
if(i > am) { b[k] = a[j++]; continue; }
if(j > ar) { b[k] = a[i++]; continue; }
b[k] = (a[i] < a[j]) ? a[i++]: a[j++];
}
for(int m=0; m < ar - al + 1; ++m)
a[m+al] = b[m];

delete [] b;
}


//归并排序算法
template <typename T>
void mergesort(T *R, int L, int H)
{
int M;
if(L < H)
{
M = (H + L)/2 ;
mergesort(R, L, M);
mergesort(R, M+1, H);
merage <T> (R, L, M, H);
}
}
//--------------------------

//=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
//堆排序算法
//=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
//取左孩子索引
int left(int i)
{
return i*2;
}

//取右孩子索引
int right(int i)
{
return i*2 + 1;
}

//通过递归将节点i的值插入到堆的合适位置
// A:0--arraysize-1,i代表数组从0开始的第几个元素,如a[2]为第3个元素
template <typename T>
void heapify(T Array[], int heap_size, int i)
{

T temp;
int lIndex, rIndex, largest;
lIndex = left(i); //取节点i的左孩子索引
rIndex = right(i);//取节点i的右孩子索引

if (lIndex <=heap_size && (Array[lIndex-1] > Array[i-1]))
largest = lIndex;
else
largest = i;

if(rIndex <=heap_size && Array[rIndex-1]> Array[largest-1])
largest = rIndex;

if(largest !=i)
{
temp = Array[largest-1];
Array[largest-1] = Array[i-1];
Array[i-1] = temp;
if(2*largest > heap_size) //左孩子为空时返回,达最大递归深度
return;
}
else //largest等于i时不需要在进行递归
return;

heapify(Array, heap_size, largest);
}

//建立堆
template <typename T>
void BuildHeap(T Array[], int size)
{
for(int i= size/2+1; i > = 1; --i)
heapify <T> (Array, size, i);
}


// 堆排序函数
template <typename T>
void HeapSort(T Array[], int size)
{
int heap_size = size;
BuildHeap <T> (Array, size);
for(int i = size; i > = 2 ; --i)
{
swap(Array[0], Array[i-1]);
heap_size = heap_size -1;
heapify <T> (Array, heap_size, 1);
}

}
//---------------------------

//交换函数 
template <typename T>
inline void mySwap(T& a,T& b)
{
T temp(a);
a = b;
b = temp;
}


//***************************************************


//-------------------选择排序函数---------------------
//***************************************************
template <typename T>
void SelectSort(T a[],int n)
{
for(int i=1; i <n; i++)
{
int minIndex = i;
for(int j=i+1; j <=n; j++)
{
minIndex = a[minIndex]> a[j] ? j : minIndex;
}
mySwap <T> (a[i],a[minIndex]);
}
}

//***************************************************
//-------------------冒泡排序函数---------------------
//***************************************************
template <typename T>
void blebSort(T a[],int n)//数组中有效位为a[1:n]
{
for(int i=1;i <n;i++)
{
for(int j=i+1;j <=n;j++)
{
if(a[i] > a[j])
mySwap(a[i],a[j]);
}
}

}

void main()
{
clock_t start, finish;
srand((unsigned)time(NULL)); //以时间作随机数生成的种子
int *pa = new int[TOTAL_NUMBER+1];


for(int i = 0 ; i <= TOTAL_NUMBER; i++)
{
pa[i] = rand();
}

start = clock();
//SelectSort <int> (pa,TOTAL_NUMBER); //选择排序
//QuickSort <int> (pa, 1, TOTAL_NUMBER); //快速排序
//blebSort <int> (pa,TOTAL_NUMBER); //冒泡排序
//mergesort <int> (pa, 0, TOTAL_NUMBER-1); //归并排序
HeapSort <int> (pa, TOTAL_NUMBER-1); //堆排序
finish = clock();

//for(int i=1;i <=TOTAL_NUMBER;i++)
//{
//cout < <pa[i] < < " ";
//}

cout < < "the cost of times: " < <finish-start < <endl;
delete [] pa;
}
[解决办法]
个人认为楼上的贴那么多,这些对人家米太大意义

给楼主改好了~~~ sort的没看,可能只是main里面的问题,不考虑程序的健壮性了,
按照输入文件,得到了-10 -4 0 1 2 9 的输出

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

const int INTEGER_NUMBER = 10;
const int STRING_LENGHT = 127;
const int SINGLE_NUMBER_LENGHT = 10;

void QuickSort(int R[], int low, int high);
int Partition(int R[], int low, int high);

// ============================================================================
// ==============================================================================

int Partition(int R[], int i, int j)
{
//~~~~~~~~~~~~~
int pivot = R[i];
//~~~~~~~~~~~~~

while (i < j) {
while (i < j && R[j] > = pivot) {
j--;
}

if (i < j) {
R[i++] = R[j];
}

while (i < j && R[i] <= pivot) {
i++;
}

if (i < j) {
R[j--] = R[i];
}
}

R[i] = pivot;
return i;
}

// ============================================================================
// ==============================================================================
void QuickSort(int R[], int low, int high)
{
//~~~~~~~~~~~
int pivotpos;
int nCount = 0;
//~~~~~~~~~~~

nCount++;

//这里的原来是调试输出的?删掉了

if (low < high) {
pivotpos = Partition(R, low, high);
QuickSort(R, low, pivotpos - 1);
QuickSort(R, pivotpos + 1, high);
}
}

// ============================================================================
// ==============================================================================
int main(void)
{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ifstream infile;
int nTempValue = 0;
int nStringLenght = 0;


int nIntegerNumber[INTEGER_NUMBER];
char cString[STRING_LENGHT];
char cTempChar[SINGLE_NUMBER_LENGHT];
string strMyString = " ";
string strTempString = " ";
int nCnt;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

infile.open( "myfile01.txt ", ios::in);
if (!infile) {
return 0;
}

while (!infile.eof()) {
infile.getline(cString, 127);
strMyString = cString;
nStringLenght = strMyString.length();
for (int i = 0;; i++) {// 这里判断 i < nStringLenght 没什么意义

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int nCommaPos = strMyString.find( ", ");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

if (nCommaPos == -1) {

// 找不到,最后一个
nIntegerNumber[i] = atoi(strMyString.c_str());
nCnt = i + 1;// 计数
break;
}

memset(cTempChar, '\0 ', 10);
strTempString = strncpy(cTempChar, strMyString.c_str(), nCommaPos);
strMyString = strMyString.c_str() + nCommaPos + 1; // 主要是要把取出的去掉

nTempValue = atoi(cTempChar);
nIntegerNumber[i] = nTempValue;
}
}

infile.close();
QuickSort(nIntegerNumber, 0, nCnt - 1 );

//~~
// 和元素的个数有关
int i;
//~~

for (i = 0; i < nCnt; i++) {
printf( "%d ", nIntegerNumber[i]);
}

return 0;
}

[解决办法]
看看这个,
然后自己找找问题咯 ~

排序算法比较程序
作者:D.R.Punk 更新时间: 2005-05-13

功能要求如下:
排序算法比较: shellsort, quicksort, heapsort, mergesort 的算法实现 ,
对同样数据集的排序时间比较。

源代码:
# include <stdio.h>
# include <time.h>

# define MAXSIZE 2000

typedef struct{
int key[MAXSIZE];
int length;
}list;

long int compCount;
long int shiftCount;

void menu(int *m)/*retun m*/
{
int i;
char menu[6][15]={ "1 CREATE ", "2 IMPORT ", "3 SORT ", "4 SHOW RESULT ",
"5 SAVE RESULT ", "6 EXIT "};
clrscr();
printf( "SORT COMPARE SYSTEM\n ");
for (i=0;i <6;i++) printf( "%s\n ",menu[i]);
printf( "\n Please Select (1-6):\n ");

scanf( "%d ",m);
}

void menusort(int *m)/*retun m*/
{
int i;
char menusort[5][15]={ "1 SHELL SORT ", "2 QUICK SORT ", "3 HEAP SORT ",
"4 MERGE SORT ", "5 ALL SORT "};

clrscr();
printf( "SORT\n ");
for(i=0;i <5;i++) printf( "%s\n ",menusort[i]);
printf( "\n Please Select (1-5):\n ");

scanf( "%d ",m);

}


void menushow(int *m)/*retun m*/
{
int i;
char menushow[4][20]={ "1 SHELL SORT RESULT ", "2 QUICK SORT RESULT ",
"3 HEAP SORT RESULT ", "4 MERGE SORT RESULT "};

clrscr();
printf( "SHOW SORT RESULT\n ");
for(i=0;i <4;i++) printf( "%s\n ",menushow[i]);
printf( "\n Please Select (1-4):\n ");

scanf( "%d ",m);
}

void menusave(int *m)
{
int i;
char menusave[4][20]={ "1 SHELL SORT RESULT ", "2 QUICK SORT RESULT ",
"3 HEAP SORT RESULT ", "4 MERGE SORT RESULT "};



clrscr();
printf( "SAVE:\n ");
for (i=0;i <4;i++) printf( "%s\n ",menusave[i]);
printf( "\n Please Select (1-4):\n ");

scanf( "%d ",m);
}

void create(list *L)
{
int i;

printf( "HOW MANY DATA?\n ");
scanf( "%d ",&((*L).length));

for(i=1;i <=(*L).length;i++)
{
printf( "\nPLEASE INPUT THE %dth DATA:\n ",i);
scanf( "%d ",&(*L).key[i]);
}
printf( "\nCREATE COMPLETE !\n ");
}


int listopen(list *L,char *filename)
{
int k=1;
FILE *data;

data=NULL;


data=fopen(filename, "rb ");

while (! feof(data))
{
fscanf(data, "%d ",&(*L).key[k]);
k++;
}
(*L).length=k-1;
}

void import(list *L)/*fix L*/
{
char filename[255];
int i;

printf( "\nPLEASE INPUT THE FILE PATH AND NAME:\n ");
scanf( "%s ",filename);

clrscr();
listopen(L,filename);
for(i=1;i <(*L).length;i++) printf( "%d ",(*L).key[i]);
printf( "\nPRESS ANYKEY RETURN TO MAINMENU...\n ");
getch();
}

void save(list L)
{
FILE *data;
char filename[255];
int r;

printf( "\nPLEASE INPUT THE FILE PATH AND NAME:\n ");
scanf( "%s ",filename);

data=fopen(filename, "wb ");
for(r=1;r <=L.length;r++) fprintf(data, "%d\n ",L.key[r]);
fclose(data);
printf( "SAVE OK! \n PRESS ANY KEY TO RETURN THE MAINMENU... ");
getch();
}


list shellsort(list L)/*retun L_SHELL*/
{
int i,j,gap,x,n;

compCount=shiftCount=0;
n=L.length;
gap=n/2;
while (gap> 0)
{
compCount++;
for(i=gap+1;i <=n;i++)
{
compCount++;
j=i-gap;
while(j> 0)
{
compCount++;
if(L.key[j]> L.key[j+gap])
{
compCount++;
x=L.key[j];shiftCount++;
L.key[j]=L.key[j+gap];shiftCount++;
L.key[j+gap]=x;shiftCount++;
j=j-gap;
}
else j=0;
}

}
gap=gap/2;
}
return L;
}

void shell(list L,list *LS,float *timeshell)/*return LS,timeshell.
MUST add an "getch "!!*/
{
clock_t start,end;


start=clock();
(*LS)=shellsort(L);
end=clock();

*timeshell=(end-start)/CLK_TCK;

printf( "\nSHELLSORT COST TIME :%f SECONDS. ",*timeshell);
printf( "Compare %d times.Shfit %d times.\n ",compCount,shiftCount);
}

int Partition(list * pL,int low,int high)
{
int pivotkey;
pL-> key[0]=pL-> key[low];shiftCount++;
pivotkey=pL-> key[low];shiftCount++;
while(low <high)
{
compCount++;
while(low <high && pivotkey <=(pL-> key[high]))
{compCount++;compCount++; --high;}


pL-> key[low]=pL-> key[high];shiftCount++;
while(low <high && (pL-> key[low]) <=pivotkey)
{compCount++;compCount++; ++low;}
pL-> key[high]=pL-> key[low];shiftCount++;
}
pL-> key[low]=pL-> key[0];shiftCount++;
return low;
}/*Partition*/

void QSort(list * pL,int low,int high)
{
int pivotloc;
if(low <high)
{
compCount++;
pivotloc=Partition(pL,low,high);
QSort(pL,low,pivotloc-1);
QSort(pL,pivotloc+1,high);
}
}/*QSort*/

list QuickSort(list pL)
{
compCount=shiftCount=0;
QSort(&pL,1,pL.length);
return pL;
}/*QuickSort*/
[解决办法]
... 其实他主要是main的读取有问题~~~ 偶已经更正在上面乐...

热点排行