What's wrong with my C program? the title is to sort n number from small to large, when i run it, everything goes fine but the number isn't been sorted. I just don't know how to solve that although i have thought for a long time.
Here is the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void selection(int *a[], int n);
int main()
{
int n;
int i;
scanf("%d", &n);
int *a[n];
int b[n];
srand((int) time(0));
for (i = 0; i < n; i++)
{
b[i] = ((int) (rand() % 100));
a[i] = &b[i];
}
selection(a, n);
return 0;
}
void selection(int *a[], int n)
{
int i;
int j;
int position;
int temp;
for (i = 0; i < n - 1; i++)
{
position = i;
for (j = i + 1; j < n; j++)
{
if (*a[i] > *a[j])
position = j;
}
temp = *a[i];
*a[i] = *a[position];
*a[position] = temp;
}
for (i = 0; i < n - 1; i++)
printf("%d\n", *a[i]);
}
I have found neither the quick sort nor the bubble sort in the presented code.
It seems you are trying to use the selection sort.
I think that the function can look the following way.
void selection_sort( int * a[], int n )
{
int i;
for ( i = 0; i < n; i++ )
{
int position = i;
int j = i + 1;
for ( ; j < n; j++ )
{
if ( *a[j] < *a[position] ) position = j;
}
if ( position != i )
{
int *temp = a[position];
a[position] = a[i];
a[i] = temp;
}
}
for ( i = 0; i < n; i++ ) printf( "%d ", *a[i] );
putchar( '\n' );
}