I'm a complete beginner in C, and I'm trying to learn how to do this selection sort algorithm to create an ascending list. But for some reason it doesn't run, and I can't seem to figure out why for an entire morning?
please tell me how I can fix it?
int main() {
int x, i, j, tempt, min;
int array[] = { 2,9,15,7,5,3,11,8,4 };
int size = sizeof(array) / sizeof(array[0]);
for (i = 0; i < (size - 1); i++)
{
min = i;
for (j = i + 1; j < size; j++)
{
if (array[j] < array[min])
{
min = j;
}
if (min != i)
{
tempt = array[i];
array[i] = array[min];
array[j] = tempt;
}
}
for (i = 0; i < (size); i++) {
printf("%d\n", array[i]);
}
}
}
This is what I got
2
9
15
7
5
3
11
8
4
--------------------------------
Process exited after 0.02851 seconds with return value 0
Press any key to continue . . .
There are two problems with your code:-
First, You are using
iinside the primary loop that you are using to sort. For example, let's think that:i=0;mingot the value ofiwhich is0jran and did it's work.i. It will start withi's initial value which is0and print the values of array tilli<size. So, we can say at the end of this loop youriwill be equal tosize. Now the value ofiis equal tosize. Now the main for loop will check the condition ifi<size-1and it's false and the main for loop will not run and your program will exit after your main for loop ran for just once.Second Problem is that even if you put the last for loop out and print it after the whole sorting(). Still, when you replace the
array[min]variable with thearray[i]variable then technically theminindex also changes because you changed the variable at this index and send the minimum variable at another location through swapping. So you should change your min to j after each swapping. After considering all these possibilities, your code should look like this:-