1 Replies - 231 Views - Last Post: 30 April 2013 - 09:44 PM Rate Topic: -----

#1 joeydal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 05-March 13

Search and sort

Posted 30 April 2013 - 08:55 PM

I need to be able to display whether or not a person searched for "is a friend" if found in the file and "isn't a friend" if not found in the file. I also need to continue processing names until "END" is typed in. Any help would be appreciated!

#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;
 }
	 
 



Is This A Good Question/Topic? 0
  • +

Replies To: Search and sort

#2 jimblumberg  Icon User is offline

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,751
  • Joined: 25-December 09

Re: Search and sort

Posted 30 April 2013 - 09:44 PM

So do you have a question or problem with the code you posted?

Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1