1

This is simple code in C (selection sort):

#include <stdio.h>
#include <stdlib.h>
#define ItemCount 10

int numbers[ItemCount] = {4,9,3,7,2,5,10,2,12,6};    

int MinNumberIndex(int start) {
    int i;
    int minindex = start;

    for (i = start + 1; i < ItemCount; i++)
        if (numbers[minindex] > numbers[i])
            minindex = i;

    return minindex;    
}


void SelectionSort() {
    int i,temp,minindex;

    for (i = 0; i < 10; i++) {
        minindex = MinNumberIndex(i);

        temp = numbers[i];
        numbers[i] = numbers[minindex ];
        numbers[minindex ] = temp;                                                                          
    }
}

int main() {
    int i;

    SelectionSort();
    for (i = 0; i < 10; i++)
        printf("%d\t",  numbers[i]);

    system("pause");    
}

And it is working ok... but if I change a little bit like this(in selectionSort function):

for (i = 0; i < 10; i++) {
    temp = numbers[i];
    numbers[i] = numbers[MinNumberIndex(i)];
    numbers[MinNumberIndex(i)] = temp;                                                                          
}

it is not working... Why? It seems to be the same.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
Domiik
  • 233
  • 1
  • 5
  • 14

3 Answers3

2

The value returned by MinNumberIndex depends on the contents of the array. You're changing the content when you do:

numbers[i] = numbers[MinNumberIndex(i)];

so the next call:

numbers[MinNumberIndex(i)] = temp;

will/can store to the wrong cell since MinNumberIndex(i) can have changed. This breaks the algorithm because you're not doing a proper swap.

Mat
  • 202,337
  • 40
  • 393
  • 406
1

Because MinNumberIndex(i) returns different values each time you call it, so the second version really isn't a value swap.

Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
1

Since MinNumberIndex(i) returns the index of the smallest element in the range [i,ItemCount-1] and your alternate version of the code modifies that range in the array between the two calls to MinNumberIndex(), you're not swapping elements.

Your alternate loop is eqivalent to:

for (i=0;i<10;i++)
        {

            temp = numbers[i];
            numbers[i] = numbers[MinNumberIndex(i)];
            numbers[i] = temp;                                                                          
        }

In a bit more detail, when this line of code is executed in the for loop:

numbers[i] = numbers[MinNumberIndex(i)];

It makes numbers[i] the minimum in the array range you're dealing with at that moment, so the next time MinNumberIndex(i) is called, it'll return i. And

numbers[i] = temp;

will just restore the array to the same state it was in at the top of the loop.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760