C Language Practice: Sorting - Selection Sort
One Way for Sorting - Selection Sort
What is selection sort?
Selection sort is a kind of sorting. It's the easiest sorting and it also uses most time.
To mention here, there are many ways of selection sorting. I'm only going to talk about the way that I see. You can surf the internet and find other ways. There are also two directions you can sort a list: from least to greatest or from greatest to least. Here I uses the least to greatest way.
What you want to do in selection sorting is that you pick the first element, and then we find the least element in the list, you swap them, then give them back to the list(what I mean here is that when you swap them, the list don't change, so you have to synchronize it with the list also). Then you take the second element, and you find the least element in the least except for the ones that we already sorted(in this case the first one), and you repeat the process above. You then take the third element, and you repeat and so on and so on until every element in the list is sorted.
Train of thought in coding:
- Step 1: We have to have many variables.
- We need because that will be the 'first', 'second' and 'third' in the paragraph above.
- We also have , which we'll use to store the 's 's value.
- Also , which is literally , which we'll use to store the least value in the list except for those already sorted.
- Finally, here comes our guest, , and for Minecraft players I don't mean teleport, I mean , which I didn't mention above. With that, since we're going to synch the list to our variables as I mentioned above, we don't necessarily know where our least value is in our unless we store it in an variable.
- Pretty annoying, huh? Long list
- Step 2: We have to have a loop that is the outer frame of our list sorting. You'll see what I mean if you look at step 3.
- Step 3: We have a nested loop. The inner part is going to help us with the sorting, while the outer part is going to keep us moving until the list is sorted. I hope that's clearer to you now.
- Step 4: IMPORTANT! Don't forget to return the in the function!
- Step 5: Get and , and get going with the function!
#include <stdio.h>
int selectionsort(int array[], int total)
{
int place = 0;
int j, h, t, tp;
for (int i = 0; i < total; i++)
{
tp = place;
j = array[place];
t = j;
for (int f = place + 1; f < total; f++)
{
if (t > array[f])
{
t = array[f];
tp = f;
}
}
int temp;
temp = t;
t = j;
j = temp;
array[place] = j;
array[tp] = t;
place++;
}
return array;
}
int main(void)
{
int total;
printf("how many numbers do you want to input?\n");
scanf("%d", &total);
int array[total];
printf("enter your number list here.\n");
for (int i = 0; i < total; i++)
{
scanf("%d", &array[i]);
}
selectionsort(array, total);
printf("your sorted list is here.\n");
for (int j = 0; j < total; j++)
{
printf("%d\n", array[j]);
}
return 0;
}