Array Selection sort in C

#include <stdlib.h>
#include <stdio.h>

#define MAXVALS 10

int main()
{
int table_fill(int a[], int n);
void print_table(int a[], int n);
int sort_table(int a[], int n);

int a[MAXVALS];
int n;

n = table_fill(a, MAXVALS);
// print_table(a, n);
sort_table(a, n);
print_table(a, n);

return 0;
}

int table_fill(int a[], int n)
{
int cnt; //Variable for counting values
int r; //Scanf's return value
int next; //Variable for increasing array values

cnt = 0;
while ((r = scanf("%i", &next)) != EOF && cnt < n)
{
if (r == 0)
{
printf("Nonnumeric data entered. Please enter a number.\n");
while (getchar() != '\n')
;
}
else
a[cnt++] = next;
}
if (r == 1)
printf("No more room in array after reading %i values.\n", cnt);

return cnt;
}

void print_table(int a[], int n)
{
int i;

for (i = 0; i < n; i++)
printf("%i\n", a[i]);
}

int sort_table(int a[], int n)
{
void swap(int a[], int i, int min_index);

int i;
int j;
int min;
int min_index;

for (i = 0; i <= n-2; i++)
{
min = a[i];
min_index = i;
for (j = (i + 1); j <= n-1; j++)
{
if (a[j] < min)
{
min = a[j];
min_index = j;
}
}
swap(a, i, min_index);
}
}

void swap(int a[], int i, int min_index)
{
int pos;

/* for (pos = i + 1; pos > 0 && min_index < a[pos - 1]; pos--)
a[pos] = a[pos - 1];
a[pos] = min_index;*/

for (pos = i + 1; pos > 0 && a[pos] < a[pos - 1]; pos++)
{
min_index = a[pos];
a[pos] = a[pos-1];
a[pos-1] = min_index;
}

}




The flush works, but the Swap wont work and the Selection Sort wont work
Please help
Thanks





Last edited on
Topic archived. No new replies allowed.