What is wrong with my selection sort function?
May 3, 2009 at 1:13am UTC
What is wrong with my selection sort function? I am trying everything.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
void sort(int array[], int numts)
{
int lowIndex, lowest;
for (int count = 0; count < (numts-1); count++)
{
lowIndex = count;
lowest = array[count];
for (int index = count + 1; index < numts; index++)
{
if (array[index] < lowest)
{
lowest = array[index];
lowIndex = index;
}
}
array[lowIndex] = array[count];
array[count] = lowest;
}
return ;
}
May 3, 2009 at 2:08am UTC
Compare what you're doing to the selection sort algorithm:
for i=0 to n-2{
find the lowest value in array[i;n-1]
if i!=lowestIndex
swap array[i] with array[lowestIndex]
}
May 3, 2009 at 3:03am UTC
Thanks for the help but I am not very versed in it so I don't fully understand. I am a little confused. Three questions:
1) What do you mean by n-2?
2) What do you mean by [i;n-1]?
3) Do you have an example of a swap function so I could see?
May 3, 2009 at 3:26am UTC
Something like this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
void selectionSort(int array[], int numts)
{
int index, lowIndex, lowest;
for (int count = 0; count < numts - 1; count++)
{
lowIndex = count;
for (index = count + 1; index < numts; index++)
{
if (array[index] < array[lowIndex])
lowIndex = index;
}
if (lowIndex != count)
{
lowest = array[count];
array[count] = array[lowIndex];
array[lowIndex] = lowest;
}
}
If so, why is this not working?
Last edited on May 3, 2009 at 3:26am UTC
Topic archived. No new replies allowed.