I was writing a selection sort, and it's not sorting properly, sometimes it works, but most of the time there is one or two numbers out of place. It's supposed to print an array of numbers, sort those numbers, then print them again. It works in debug mode, but whenever I run it regularly, that's when the problems start happening.
Note: In case your wondering why there's a while loop at the beginning that's because I'll be working on repeating it later.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int print(int array[4]);
int main(void)
{
bool loop = true;
//main loop
while (loop)
{
//array
int array[5];
//assign numbers
int seconds= time(NULL);
printf("%d\n", seconds);
srand(seconds);
for(int i = 0; i <= 4; i++)
{
//random number between 0 and 5
int r = rand();
array[i] = r % 6;
}
//print numbers
for(int i = 0; i <= 4; i++)
{
printf("%d ", array[i]);
}
printf("\n");
//sort
int temp;
for(int i = 0; i <= 4; i++)
{
//set minimum
int min = array[i];
//check minimum value
for(int j = i + 1; j <= 4; j++)
{
if(min > array[j])
{
min = array[j];
temp = j;
}
}
//swap minimum values
int first = array[i];
array[i] = min;
array[temp] = first;
}
for(int i = 0; i <= 4; i++)
{
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
}
int print(int array[4])
{
return 0;
}
Sample Output:
1584216938
3 5 1 4 1
1 1 3 3 4