Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can my selection sort work? 1

Status
Not open for further replies.

amn95

Technical User
Sep 16, 2002
3
US
# include <iostream>
# include <cstring>
using namespace std;

int main()
{
char text [81];
char *word ;
int count=0;
int minValue,minIndex;


cout << &quot;Please enter a sentence &quot;;
cout << &quot;not exeeding 30 words:\n&quot;<<endl;
cin.getline(text,31);//


for (int i=0; i < count; i++ )
{
cout << word <<endl;
}

word = strtok (text, &quot; &quot;);
if (word < minValue)
{
minValue = word ;
minIndex = i;
}


while (word != NULL)
{
cout << word <<endl;
word = strtok(NULL,&quot; &quot;);
}
cout <<&quot; \n&quot;<<endl;



return 0;
}
 
What are you trying to sort? Are you trying to sort the words in ascending/descending order or do you just want to print out all the words.
 
I'm trying to sort in ascending order and to print them out in ascending order.
 
Selection sort .... haven't heard about it.

However I am pretty sure your code doesn't do any sort.

A couple of problems with your code :

1) You compare an integer with a char-pointer ...
2) You compare word and minvalue without initialising minvalue.
3) Your first loop (count) doesn't seem right ....

Try and debug your code ....

/JOlesen
 
First plan your code in comment form, then fill in the code. Looks like what you've got is

1) Get data
2) Print data which has been broken up
3) Break up data

Also, you are not allocating any storage for the data. Anyway, this is roughly what it should look like. Note the comments: write those first before you start coding.

# include <iostream>
# include <cstring>
using namespace std;

const int maxwords = 30;

int main()
{
char text [81];
char *word[maxwords] ;
int count=0, i, j;
int minIndex;
char* swap;

/* Get the data */
cout << &quot;Please enter a sentence &quot;;
cout << &quot;not exeeding &quot; << maxwords << &quot; words:&quot;<<endl;
cin.getline(text,sizeof (text));//

/* Break it up into words */
word[count] = strtok (text, &quot; &quot;);
while (word[count] != 0)
{
++count;
word[count] = strtok (0, &quot; &quot;);
}

/* Sort the words using selection sort */
for (i = 0; i < (count - 1); i++)
{
/* Find the lowest */
minIndex = i;
for (j = i + 1; j < count; j++)
{
if (strcmp (word[minIndex], word[j]) > 0)
minIndex = j;
}

/* Swap if we are not the lowest */
if (minIndex != i)
{
swap = word[minIndex];
word[minIndex] = word;
word = swap;
}
}

/* Print the words */
for (i=0; i < count; i++ )
{
cout << word <<endl;
}

return 0;
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top