By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,001 Members | 1,462 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,001 IT Pros & Developers. It's quick & easy.

Selection Sort

P: 1
Okay, I have this homework assignment which is to sort a 2D array of characters using selection sort.

I've written the selection sort but I can't seem to get it working. (it's not sorting!)

Please tell me what I'm doing wrong, thanks.

Expand|Select|Wrap|Line Numbers
  1. void selectionSort(char array[][SIZE], int rows)
  2. {
  3.     const int size = 17;
  4.     int startScan, minIndex, index;
  5.     char minValue[NUM_NAMES][size];
  6.  
  7.     for (startScan = 0; startScan < (rows - 1); startScan++)
  8.     {
  9.         minIndex = startScan;
  10.         strncpy(minValue[0], array[startScan], 20);
  11.         for (index = startScan + 1; index < rows; index++)
  12.         {
  13.             if (strcmp(array[index], minValue[NUM_NAMES]) < 0)
  14.             {
  15.                 strncpy(minValue[0], array[index], 20);
  16.                 minIndex = index;
  17.  
  18.             }    
  19.         }
  20.     strncpy(array[startScan], array[minIndex] , 20);
  21.  
  22.     }
  23. }
Nov 18 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
Originally Posted by
void selectionSort(char array[][SIZE], int rows)
{
const int size = 17;
int startScan, minIndex, index;
char minValue[NUM_NAMES][size];

for (startScan = 0; startScan < (rows - 1); startScan++)
{
minIndex = startScan;
strncpy(minValue[0], array[startScan], 20);
for (index = startScan + 1; index < rows; index++)
{
if (strcmp(array[index], minValue[NUM_NAMES]) < 0)
{
strncpy(minValue[0], array[index], 20);
minIndex = index;

}
}
strncpy(array[startScan], array[minIndex] , 20);

}
}
Several things:
1) What is the 17 for??? You never use it.
2) Your function argument is an array of strings. That means its an array of char*
3) Your minIndex should start wirth array[0] and avance to array[1] on the next cycle of the loop
4) When you compare strings, you swap the pointers. You cannot swap the strings themselves since they are different lengths. I expect that's what the 20 was for. A hack to avoid a crash.
5) the outer loop shoukld run from 0 to rows.
6) the inner loop should frim from the outer loop index to rows.
Nov 21 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.