1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <iostream>
#include <fstream>
#include <string>
#include<sstream>
using namespace std;
char name;
void bubbleSort (string names[], int size=0);
int binarySearch(string names[], int size, string value);
void displayit (string names[], int count);
int main ()
{
ifstream infile;
string names[200], valu, arrayLength;
int count=0, size=0;
infile.open("myFriends.dat");
if (!infile)
cout<< "Could not open myfriends file"<<endl;
else
{
while (getline (infile, names[count]))
{count++;}
displayit ( names, count);
bubbleSort(names, size);
cout<< "Please enter a name or END to terminate: "<<endl;
getline (cin, names[count]);
binarySearch(names,size,valu);
}
cout<< names[count]<< " is my friend"<<endl;
infile.close ();
system ("pause");
return 0;
}
void displayit (string names[], int count)
{
for (int i=0; i<count; i++)
cout<< names[i]<<endl;
}
void bubbleSort (string names[], int size)
{
bool swap;
string temp;
do
{
swap=false;
for (int count=0; count <(size-1); count++)
{
if (names[count]> names[count+1])
{
temp=names[count];
names[count]=names[count+1];
names[count+1]=temp;
swap=true;
}
}
} while (swap);
}
int binarySearch(string names[], int size, string value)
{
int first = 0,last = size - 1, middle, position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (names[middle] == value)
{
found = true;
position = middle;
}
else if (names[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
|