I am trying to implement a bubble sort algorithm, but with 3 functions, a gen_array to generate the array given a size and a maximum for the values and a sort to sort the values in a bubble sort way. I can't get the sort part to work. However, the gen_array funcion is doing what it is supposed to and working when I call it and print its values on main().
Here is the code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int gen_array(int ** list, int size, int max) {
*list = (int *)malloc(size * sizeof(int));
if (*list == NULL){
printf("ERROR: out of memory\n");
return 1;
}
srand( (unsigned)time( NULL ) );
for (int i = 0; i < size; ++i) {
(*list)[i] = rand() % max;
}
return 0;
}
int sort(int * a, int s) {
int *temp;
for (int i = 1; i < s; ++i) {
for (int j = 0; j < i - 1; ++j) {
if (*(a + i) > *(a + i + 1)) {
*(a + i) = temp;
*(a + i) = *(a + i + 1);
*(a + i + 1) = temp;
}
}
}
return 0;
}
int main() {
int size;
printf("array Size --> ");
scanf("%d", &size);
int * a;
gen_array(&a ,size, 100);
for (int i = 0; i < size; ++i) {
printf("%d ", a[i]);
}
printf("\n");
sort(a, size);
for (int j = 0; j < size; ++j) {
printf("%d", a[j]);
}
free(a);
getchar();
return 0;
}
After following @mch's comment I got this output,
Array Size --> 5
1 4 46 4 51
1 4 4 0 0
Process finished with exit code 0
So, the list is generating with 5 elements, but the sort part isn't working, I believe the sort code is right (the bubble algorithm), but the pointers aren't being used correctly? Perhaps I should copy the contents of the array with realloc() ?