it should be simple but I got stuck with this... i did something like this but it doesn't work... can anyone tell me why???
#include %26lt;stdio.h%26gt;
main()
{int a,array[50],n,m,border,max,buffer,step;
printf("Input number of elements in array:");
scanf("%d",%26amp;a);
for(n=0;n%26lt;a;n++) {
printf("input %d. element of array:",n+1);
scanf("%d",%26amp;array[n]);
}
border=a+1;
for(n=0;n%26lt;a;n++) {max=array[0];
for(m=0;m%26lt;border;m++) {if (array[m]%26gt;max) {max=array[m];
step=m;}
}
buffer=array[border];
array[border]=array[step];
array[step]=buffer;
border--;
}
for(n=0;n%26lt;a;n++) {
printf("%d. element: %d\n",n+1,array[n]);
}
getchar();
scanf("%d",%26amp;n);
}
Do you know a C language program for ordering numbers in array or can you correct mine?
Try this:
#include %26lt;stdio.h%26gt;
main()
{
int size,array[50],n,m,border,max,buf,step;
int i, j, temp;
printf("Input number of elements in array:");
scanf("%d",%26amp;size);
for(n=0;n%26lt;size;n++) {
printf("input %d. element of array:",n+1);
scanf("%d",%26amp;array[n]);
}
for (i=(size-1);i%26gt;=0; i--)
{
for(j=1;j%26lt;=i;j++)
{
if(array[j-1]%26gt;array[j])
{
temp=array[j-1];
array[j-1]=array[j];
array[j]=temp;
}
}
}
for(n=0;n%26lt;size;n++)
printf("%d. element: %d\n",n+1,array[n]);
}
HERE IS MY OUTPUT:
Input number of elements in array:8
input 1. element of array:6
input 2. element of array:2
input 3. element of array:3
input 4. element of array:5
input 5. element of array:1
input 6. element of array:4
input 7. element of array:5
input 8. element of array:7
1. element: 1
2. element: 2
3. element: 3
4. element: 4
5. element: 5
6. element: 5
7. element: 6
8. element: 7
Reply:If you are seeking to know how sorting algorithms work, its a different matter, otherwise you should use the standard library function qsort
#include %26lt;stdlib.h%26gt;
void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));
From your code, it seems you use windows, but i am sure windows stdlib would have this function too. (Its POSIX)
to invoke, you write a comparison function . If you are sorting integers, this would work
int
compfn(void *int1, void *int2)
{
int a = *(int *)int1;
int b = *(int *)int2;
if(a%26gt;b)
reurn 1;
if(a%26lt;b)
return -1;
/* equal */
return 0;
}
and then call the qsort function as
qsort(array,50,sizeof(int),compfn);
to get a sorted array
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment