Selection Sort

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neyugncul
    New Member
    • Nov 2007
    • 1

    #1

    Selection Sort

    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.

    [code=c]
    void selectionSort(c har 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(minValu e[0], array[startScan], 20);
    for (index = startScan + 1; index < rows; index++)
    {
    if (strcmp(array[index], minValue[NUM_NAMES]) < 0)
    {
    strncpy(minValu e[0], array[index], 20);
    minIndex = index;

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

    }
    }[/code]
    Last edited by Ganon11; Nov 21 '07, 06:34 PM. Reason: Changing [QUOTE] tags to [CODE] tags.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Originally posted by neyugncul
    Originally Posted by
    void selectionSort(c har 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(minValu e[0], array[startScan], 20);
    for (index = startScan + 1; index < rows; index++)
    {
    if (strcmp(array[index], minValue[NUM_NAMES]) < 0)
    {
    strncpy(minValu e[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.

    Comment

    Working...