Hi, i am given an array of atomic numbers, and I need to arrange them in order from 1-100 or something.

the program i wrote is this

for(fill = 0; fill < (m-1); ++fill)
   {
     if(atomic_num[index_of_min] <= atomic_num[fill])
     {
     temp = atomic_num[index_of_min];
     atomic_num[index_of_min] = atomic_num[fill];
     atomic_num[fill] = temp;
     }
    ++index_of_min;
   }

  
   for(j = 0; j < (m-1); j++)
      fprintf(outp,"%d\n", atomic_num[j]);

gives these the output below. It only orders 88 in the right order. How should I order all the elements in the right order.


the array of elements
1
1
1
50
84
88
1
1
1
1
1
1
11
20
84

ordering only 88.

1
1
1
50
84
1
1
1
1
1
1
11
20
84
88

how should i make them order 1,1, 1, 1, 11, 20, 84, 84, 88 something like this?


thanks,

Recommended Answers

All 4 Replies

You can using qsort() function which is come with <stdlib.h> header. Here the example of how to use this function:

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

int CompareFunction(const void *p1, const void *p2)
{
    if (*(const int*)p1 > *(const int*)p2)
        return 1;
    else return -1;
    return 0;
}

int main()
{
    int i, a[5] = {5, 3, 2, 8, 1};
    qsort(&a, 5, sizeof(int), CompareFunction);
    for(i = 0; i < 5; i++)
        printf("%d  ", a[i]);
}
commented: yuk -2
for(fill = 0; fill < (m-1); ++fill)
   {
     if(atomic_num[index_of_min] <= atomic_num[fill])
     {
     temp = atomic_num[index_of_min];
     atomic_num[index_of_min] = atomic_num[fill];
     atomic_num[fill] = temp;
     }
    ++index_of_min;
   }

  
   for(j = 0; j < (m-1); j++)
      fprintf(outp,"%d\n", atomic_num[j]);

It looks to me that you were trying to implement a bubble sort.
For that you need two index variables and two loops.

/* indexes for loops */
    int a, b;

    /* How many elements atomic_num has? */
    int size = sizeof atomic_num / sizeof ( int );

    /* temporal storage */
    int temp;


    for ( a = 0; a < size - 1; a++ )
    {
        for ( b = a + 1; b < size; b++ )
	{
	    if ( atomic_num[a] > atomic_num[b] )
            {
		temp = atomic_num[a];
		atomic_num[a] = atomic_num[b];
		atomic_num[b] = temp;
	    }
	}
	/* printf( "%d\n", atomic_num[a] ); uncomment for displaying */
    }

yeah it works, but I also need to printf the name of the element and the symbol along with atomic numbers. How would I do that? Would i use sturctures or parallel array and switch indexes or somethings? I don't know how I would go about it?

Member Avatar for iamthwee

You could use a struct, or if the idea is too abstract for you, toy with the idea of parallel arrays, like you said.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.