I'm having some trouble with my sort function which also uses the swap function to work. I have been trying to find my mistake but cant find it. the rest of the code works perfectly, only the sort function doesn't work (it doesn't sort anything.)
I will leave the code here if anybody has any ideas of how to solve my problem please reply.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sort(int *values, int n);
void swap(int arr[], int i);
void populate(int arr[]);
const int arraysize = 10;
int main()
{
srand((long int) time(NULL));
int ela[10] = {0};
populate(ela); // populates with random values
printf("before func\n");
for(int i = 0; i < arraysize; i++)
{
printf("%i\n", ela[i]);
}
sort(ela, arraysize); // this is the function that is not working
printf("\n\nafter func\n");
for(int i = 0; i < arraysize; i++)
{
printf("%i\n", ela[i]);
}
return 0;
}
void sort(int *values, int n)
{
int count = 1;
while(count != 0)
{
count = 0;
for (int i = 0; i < n; i++) {
if(values[i] > values[(i + 1)] && values[(i + 1)] != '\0')
{
swap(values, i);
count++;
}
if (count == 0) break;
}
}
}
void swap(int arr[], int i)
{
int save = arr[i];
arr[i] = arr[i+1];
arr[i + 1] = save;
return;
}
void populate(int arr[])
{
for(int i = 0; i < arraysize; i++)
{
arr[i] = (rand() % 15);
}
}
void sort(int *values, int n)
{
int count = 1;
while(count != 0)
{
count = 0;
for (int i = 0; i < n-1; i++) {
if(values[i] > values[(i + 1)] )
{
swap(values, i);
count++;
}
//if (count == 0) break;
}
}
}
I doubt this would never be true values[(i + 1)] != '\0'
as the values are integers..So running the for loop until the condition i<n-1
would work fine as you are swapping i+1
element with i
.
And also if (count == 0) break;
inside your for loop should be removed as the loop would break if there is some input like 2 3 2 1
and so wouldn't sort .
Working Ideone: http://ideone.com/k1LJau