Skip to main content
Improved formating
Source Link
wallek876
  • 1.4k
  • 7
  • 15

I am trying to sort the array below using Selection Sort procedure:

array [] = {5,4,3,2,1}

array [] = {5,4,3,2,1}

However, when I run the code it sort the array as 12222. It clearly stops sorting after 2. I suspect the problem is where I am trying to swap values but not sure what I am doing wrong. Please help!

for (int i = 0; i < n-1; i++) { int smallest = values [i]; int position = i;

for (int i = 0; i < n-1; i++)
    {
        int smallest = values [i];
        int position = i;
        
        for (int j = i + 1; j < n; j++)
        {
            if (values [j] < smallest)
            smallest = values [j];
            position = j;
        }
        
        int tmp = values [i];
        values [i] = smallest;
        values [position] = tmp;
    }

I am trying to sort the array below using Selection Sort procedure:

array [] = {5,4,3,2,1}

However, when I run the code it sort the array as 12222. It clearly stops sorting after 2. I suspect the problem is where I am trying to swap values but not sure what I am doing wrong. Please help!

for (int i = 0; i < n-1; i++) { int smallest = values [i]; int position = i;

    for (int j = i + 1; j < n; j++)
    {
        if (values [j] < smallest)
        smallest = values [j];
        position = j;
    }
    
    int tmp = values [i];
    values [i] = smallest;
    values [position] = tmp;
}

I am trying to sort the array below using Selection Sort procedure:

array [] = {5,4,3,2,1}

However, when I run the code it sort the array as 12222. It clearly stops sorting after 2. I suspect the problem is where I am trying to swap values but not sure what I am doing wrong. Please help!

for (int i = 0; i < n-1; i++)
    {
        int smallest = values [i];
        int position = i;
        
        for (int j = i + 1; j < n; j++)
        {
            if (values [j] < smallest)
            smallest = values [j];
            position = j;
        }
        
        int tmp = values [i];
        values [i] = smallest;
        values [position] = tmp;
    }
Source Link
Malik
  • 13
  • 2

Select Sort code not working

I am trying to sort the array below using Selection Sort procedure:

array [] = {5,4,3,2,1}

However, when I run the code it sort the array as 12222. It clearly stops sorting after 2. I suspect the problem is where I am trying to swap values but not sure what I am doing wrong. Please help!

for (int i = 0; i < n-1; i++) { int smallest = values [i]; int position = i;

    for (int j = i + 1; j < n; j++)
    {
        if (values [j] < smallest)
        smallest = values [j];
        position = j;
    }
    
    int tmp = values [i];
    values [i] = smallest;
    values [position] = tmp;
}