I got the sort function to work! yay us!
Now, where do I make the call to the search function?
Code:
#include <iostream.h>
#include <string.h>
#include <fstream.h>
// this program is supposed to read a list of names from a file and then bubble sort them alphabeticaly
// and allow for binary search.
const int max=100;
int initialize_input(char inname[], ifstream& input_stream)
{
cout<<"Please type name of input file to sort: ";
cin>>inname;
input_stream.open(inname);
if (input_stream.fail()!=0)
{
cout<<"Failure to open input file--sorry";
return -1;
}
else
return 0;
};
int initialize_output(char outname[], ofstream& output_stream)
{
cout<<"Please type name of sorted output file: ";
cin>>outname;
output_stream.open(outname);
if (output_stream.fail()!=0)
{
cout<<"Failure to open output file--sorry";
return -1;
}
else
return 0;
};
void bubblesort(char table[max][max],int array_size)
{
char temp[max];
for(int count_1=0;count_1<array_size;count_1++)
{
cout<<"outer loop\n";
for(int count_2=0;count_2<array_size-1;count_2++)
{
cout<<"inner loop\n";
if(strcmp(table[count_2], table[count_2+1])>0)
{
cout<<"SWAPPING"<<count_2<<endl;
strcpy(temp,table[count_2]);
strcpy(table[count_2],table[count_2+1]);
strcpy(table[count_2+1],temp);
}
}
}
return;
}
int binary_search(int array[],int array_size,int element)
{
int start=0;
int end=array_size-1;
int middle;
int position=-1;
middle=(start+end)/2;
do
{
if(element<array[middle])
end=middle-1;
else if(element>array[middle])
start=middle+1;
middle=(start+end)/2;
}
while(start<=end && array[middle]!=element);
if(array[middle]==element)
position=middle;
return position;
}
void main ()
{
ifstream income;
ofstream outgo;
char answer; char inname[15]; char outname[15];
char line[max];
char names[max][max];
int array;
int test;
int count;
int array_size;
int element;
do{
cout<<"Beginning DO\n";
test=initialize_input(inname,income);
if (test==-1)
return;
count=0;
test=initialize_output(outname,outgo);
if (test==-1)
return;
while (income.getline(names[count],100) )
{
cout<<names[count]<<endl;
count++;
};
cout<<"There are "<<count<<" lines in this file.\n";
bubblesort(names, count);
cout<<endl<<"Sorted Names: "<<endl;
for (int which=0;which<count;which++)
{
cout<<names[which]<<endl;
outgo<<names[which]<<endl;
strcpy(line,names[which]);
};
cout<<"The sorted version of the file has been written to: "<<outname<<endl;
income.close();
outgo.close();
// binary_search(array,array_size,element);
cout<<"Would you like to run again('Y' to continue)?\n";
cin>>answer;
cout<<"your answer was:"<<answer<<'!';
}while (answer=='Y');
};