``````void Selection_Sort(int SUM_1[], int n){
int Lid, tmp;

for (int i = 0; i < n - 1; i++){
Lid = i;
for (int j = i + 1; j < n; j++){
if (SUM_1[j] != 0 && SUM_1[Lid] != 0 && SUM_1[j] < SUM_1[Lid]){
Lid = j;
}
tmp = SUM_1[i]; SUM_1[i] = SUM_1[Lid]; SUM_1[Lid] = tmp;
}
}
}
``````

The reason why I wrote the above code is,
the array SUM_1[] is something like this, {0, 1, 0, 3, 0, 5, 6},
but the result I wanted after going through Selection_Sort is {1, 3, 5, 6, 0, 0, 0}. not {0, 0, 0, 1, 3, 5, 6}.
I seems that I did it wrong.

Edited by Reverend Jim: Moved to programming forum

2
Contributors
1
12
Views
2 Years
Discussion Span
Last Post by tinstaafl

A couple of things in your code, set Lid to the highest index instead of i and do the swap after the j loop finishes:

``````void Selection_Sort(int SUM_1[], int n)
{
int Lid, tmp;
for (int i = 0; i < n; i++)
{
Lid = n - 1;
for (int j = i + 1; j < n; j++)
{
if (SUM_1[j] != 0 && SUM_1[j] < SUM_1[Lid])
{
Lid = j;
}
}
tmp = SUM_1[i]; SUM_1[i] = SUM_1[Lid]; SUM_1[Lid] = tmp;
}
}
``````

Edited by tinstaafl

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.