I was trying to write a simple sort function to sort int arrays, and I looked into some simple algorithms like bubble sort. I have written the following code, and it does an OK job to sort int arrays, in an ascending order:
void bubble_sort(float *scores, int size) {
int i = 0,j = 0;
float container = 0;
for(i = 0; i < size - 1; i++) {
for(j = 0; j < size - i - 1; j++) {
if(scores[j] > scores[j + 1]) {
container = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = container;
}
}
}
}
Then I thought of how I would usually sort a set of integers on a piece of paper, and I thought why not write a code that would do the same thing. But it turns out it is not as simple as I thought it would be at first glance. I noticed that I usually use a simple algorithm to sort a set of integers in an ascending order, using the following method:
assume the set {4, 8, 1, 9, 0}
- first I create an empty set that has five empty places.
{ , , , , } - I look for the minimum in the set, which is 0 in this case.
- and then I add it to the first empty place in my new set:
{0, , , , } - finally I delete the element I used from the original set:
{4, 8, 1, 9} - I repeat the above process until there are no more elements left in my original set.
- Now I have an ordered set.
So I went ahead and wrote a small function that can find the minimum in an array:
int minimum(int *array, int size) {
int i, min = array[0];
for(i = 1; i < size; i++) {
if(array[i] < min) {
min = array[i];
}
}
return min;
}
I was going to write a function that would take an array and sort it, until I realized I can't delete items from an array. I’m at a loss here, what should I do next?