sorting strings

This is a discussion on sorting strings within the C++ Programming forums, part of the General Programming Boards category; Hi programmers. I am trying to sort strings with this bubble sort but something is not right. I do not ...

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    5

    sorting strings

    Hi programmers.
    I am trying to sort strings with this bubble sort but something is not right. I do not think I am declaring properly temp???

    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    
    
    int main()
    {
    	const int NUM_NAMES = 20, SIZE = 17;
    	int results;
    	string name;
    	string names[NUM_NAMES][SIZE] = {"Collins, Bill", "Smith, Bart", "Allen, Jim",
    		"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
    		"Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
    		"Looney, Joe", "Wolfe, Bill", "James, Jean",
    		"Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
    		"Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
    		"Pike, Gordon", "Holland, Beth" };
    
    
    	//Sorting the array//
    
       bool swap;
       string temp;
    
       do
       {
          swap = false;
          for (int count = 0; count < (NUM_NAMES - 1); count++)
          {
             if (names[count] > names[count + 1])
             {
                temp = names[count];
                names[count] = names[count + 1];
                names[count + 1] = temp;
                swap = true;
             }
          }
       } while (swap);
    }
    Last edited by sid13; 03-11-2011 at 11:38 PM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,752
    What problem?

    Does it compile? If not, post your error messages.
    Does it run and crash? If so, post your diagnostic
    Does it run, but produce incorrect output? If so, tell us.

    Don't just dump the code and say "it doesnt' work" and expect us to work out what you think you want.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Feb 2011
    Posts
    5
    I faund the problem. It was not permiting me to asaign names[count] to temp
    temp = names[count]
    it was the wrong way of doing it

    but after i read for last 4hrs i faund the solution .


    Code:
       bool swap;
       char temp[17];
    
       do
       {
          swap = false;
          for (int count = 0; count < (size - 1); count++)
          {
             if (strcmp(array1[count],array1[count + 1]) > 0)
             {
                strcpy(temp, array1[count]);
                strcpy(array1[count], array1[count + 1]);
                strcpy(array1[count + 1], temp);
                swap = true;
             }
          }
       } while (swap);
    }
    I will be more descriptive next time
    Last edited by sid13; 03-12-2011 at 02:52 AM.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,752
    The problem would seem to have been this then.
    string names[NUM_NAMES][SIZE]

    You had a 2D array of strings.
    What you really wanted was
    string names[NUM_NAMES]

    Then your attempted assigment would have worked.

    Note that you're using a C++ std::string in your original code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Programming King Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Middle of NoWhere
    Posts
    320
    In your first post, your main() has return type integer, and you are not returning anything to the OS, so compiler must give the error message at compile time....
    Didn't it?
    I don't care if someone doesn't like me, i was not put on earth to entertain everyone.

    No King, no Queen, I am the ACE of battle.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,901
    It must not, because the standard says that if no return statement is put in main, it will implicitly return 0.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Programming King Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Middle of NoWhere
    Posts
    320
    Quote Originally Posted by Elysia View Post
    It must not, because the standard says that if no return statement is put in main, it will implicitly return 0.
    Okay... I didn't know that....
    I don't care if someone doesn't like me, i was not put on earth to entertain everyone.

    No King, no Queen, I am the ACE of battle.

  8. #8
    Registered User
    Join Date
    Feb 2011
    Posts
    5
    Ok, I did the program and it works. The program takes the name to be searched, then arranges the names alphabetically and then finds the name by binary search. However, you can see that I am hardcoding the parameters of the functions.

    int binarySearch(char[20][17], int, char[1][17]);
    void sort(char[20][17], int);

    I am doing this because when I try to pass the values as a constants in this way it gives me an error

    int binarySearch(char[NUM_NAMES][ SIZE], int, char[1][ SIZE]);
    void sort(char[NUM_NAMES][ SIZE], int);

    error C2065: 'NUM_NAMES' : undeclared identifier
    error C2065: ‘SIZE’: undeclared identifier



    So my question is, how can I pass the array of cstrings char names to my functions and in the same time using NUM_NAMES & SIZE without hard coding their values.
    All help is apreciated. Thanks to all,

    there is the conplited code

    Code:
    /* Name Search
     This program frst sorts the array and then demonstrates 
     the binarySearch function, which performs a binary search on an integer array
     to find the name by comparing strings.
    
    */
    
    
    #include <iostream>
    #include <cstring> //for use with c strings
    using namespace std;
    
    // Function prototype
    int binarySearch(char[20][17], int, char[1][17]);	//searching function
    void sort(char[20][17], int);						//sorting function
    
    int main()
    {
    	const int NUM_NAMES = 20, SIZE = 17;
    	int results;			//value returned if name faund or not
    	char name[1][SIZE];		//name string for input by user
    	char names[NUM_NAMES][SIZE] = {"Collins, Bill", "Smith, Bart", "Allen, Jim",
    		"Griffin, Jim", "Stamey, Marty", "Rose, Geri",
    		"Taylor, Terri", "Johnson, Jill", "Allison, Jeff",
    		"Looney, Joe", "Wolfe, Bill", "James, Jean",
    		"Weaver, Jim", "Pore, Bob", "Rutherford, Greg",
    		"Javens, Renee", "Harrison, Rose", "Setzer, Cathy",
    		"Pike, Gordon", "Holland, Beth" };
    
    	cout <<"Enter the name to search: ";
    	cin.getline(name[0], SIZE);						//line input which count spaces as well								
    
    	sort(names, NUM_NAMES);							//calling function to sort the array in alphabetical order
    
    	results = binarySearch(names, NUM_NAMES, name);	//calling function to search for name
    
    	if (results == -1){
    		cout << "The name does not exist in the array.\n";
    	}
    	else{
    
    		cout << "The name is found at element " << results;
    		cout << " in the array.\n";
    	}
    	return 0;
    }
    
    //Definition of function sort
    //This function is a selection sort function, which performs
    //an ascending order selection sort on array.
    //Perimeter size is the number of element in the array, with NUM_NAMES
    //as a argument.
    
    void sort(char array1[20][17], int size){
    
    	int start, minIndex; 
    	char minValue[17];  //stores the minimum value with each loop iteration
    
    	for(start = 0; start < (size - 1); start++){
    		minIndex = start;
    		strcpy(minValue, array1[start]);				//strcpy coppies strings
    		
    			for(int i = start + 1; i < size; i++){     //the inner for loop searches for the name with the
    				if(strcmp(array1[i], minValue) < 0){	//lowest alphabetical order, strcmp checks for alphabetical position 
    					strcpy(minValue, array1[i]);
    					minIndex = i;
    				}
    			}
    		strcpy(array1[minIndex], array1[start]);
    		strcpy(array1[start], minValue);
    	}
    }
    
    // Definition of binarySearch function                          
    // The binarySearch function performs a binary search on an     
    // integer array. array, which has a maximum of NUM_NAMES        
    // elements, is searched for the name stored in char name. If the 
    // number is found, its array subscript is returned. Otherwise, 
    // -1 is returned indicating the value was not in the array.  
    
    int binarySearch(char array1[20][17], int size, char name[1][17]){
    
    	int first = 0,             // First array element
    		last = size - 1,       // Last array element
    		middle,                // Mid point of search
    		position = -1;         // Position of search value
    	bool found = false;        // Flag
    
    	while (!found && first <= last){
    
    		middle = (first + last) / 2;                    // Calculate mid point
    		if (strcmp(array1[middle], name[0]) == 0){      // If value is found at mid
    
    			found = true;
    			position = middle;
    		}
    		else if(strcmp(name[0], array1[middle]) < 0){ // If value is in lower half
    			last = middle - 1;
    		}
    		else{
    			first = middle + 1; // If value is in upper half
    		}
    		
    	}
    	return position;   //the position of the name searched in the array 
    }
    Last edited by sid13; 03-12-2011 at 06:55 PM.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Posts
    22,901
    Use std::string for the strings and std::vector for the arrays.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting an array of strings
    By porstart in forum C Programming
    Replies: 3
    Last Post: 02-22-2011, 10:43 PM
  2. Sorting Array of Strings
    By nair in forum C Programming
    Replies: 6
    Last Post: 10-09-2010, 12:10 PM
  3. strings, sorting
    By kocika73 in forum C Programming
    Replies: 4
    Last Post: 02-18-2006, 04:29 PM
  4. Replies: 2
    Last Post: 02-23-2004, 06:34 AM
  5. Sorting strings to speed up search?
    By Mox in forum C++ Programming
    Replies: 5
    Last Post: 09-10-2001, 01:17 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21