0
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(int *a, int *b){
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(void){
int s = 5;
int size[s];
size[0] = 1;
size[1] = 321;
size[2] = 2;
size[3] = 42;
size[4] = 21;
for(int i = 0; i <= s - 2; i++){
    int min = i;
    for(int j = i + 1; j <= s; j++){
        if(size[j] < size[min]){
            min = j;
        }
    }
    if(min != i){
        swap(&size[min], &size[i]);
    }
}
printf("[");
for(int i = 0; i <= s - 1; i++){
    printf("%i,", size[i]);
}
printf("]\n");    
}

When I run selection, it doesnt sort my code, it replaces one of my list values with some garbage value and when I ran it through gdb I noticed that my minimum keeps going up even though its not supposed to. Help?

5
  • It sorts the array when I run it. [1,2,21,42,321,] is the print result. – curiouskiwi Aug 21 '15 at 5:51
  • Yup, works for me too. Maybe you didn't save the current version and are running a previous version? – Cliff B Aug 21 '15 at 6:20
  • [-1073843973,1,2,21,42,] I got this output, it is up to date – user1571 Aug 21 '15 at 18:52
  • @user1571 in the last iteration of the nested for loop, j is not valid index for the array size. – Kareem Aug 22 '15 at 21:01
  • FYI, a more concise way of declaring an array is int size[] = {1,321,2,42,21} – chad Aug 25 '15 at 20:40
0

You are comparing j with 5 (j<=5) which is not a valid index of the array, hence the garbage value

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .