I try to create a function which arranges the elements of an array in ascending order. But the result isn't good. I think I have forgotten one thing... thanks for your help.
#include <stdio.h>
void ft_sort_int_tab(int *tab, int size) {
int i;
int j;
int temp;
size -= 1;
i = 0;
while (i < size) {
if (tab[i] > tab[i + 1]) {
temp = tab[i];
tab[i] = tab[i + 1];
tab[i + 1] = temp;
}
i++;
}
}
int main(void) {
int tab[9] = {9, 5, 2, 3, 8, 4, 16, 20, 24};
ft_sort_int_tab(tab, 9);
for (int i = 0; i < 9; i++) {
printf("%d ", tab[i]);
}
}
The result : 5 2 3 8 4 9 16 20 24
Your code swaps the two elements if needed, but then moves on to the next position in the array. In the beginning of your example, the 9 and 5 get swapped, so 5 ends up in the first position, but 5 never gets compared to other elements.
There are lots of sorting algorithms out there, and you should read about them. The one that your code seems most similar to is called “bubble sort.” To get there, modify your code do that it makes multiple passes over the array until the array is completely sorted. If you made a second pass, for example, the 5 and 2 would get swapped, and you’d be closer to a sorted result.
Bubble sort is not the fastest way to sort, but it’s easy to understand. Other ways include quicksort, mergesort, and heapsort. Wikipedia can explain each of those, and they’re worth looking into if your need better performance.