Thursday, July 30, 2009

Write a C program for sorting numbers.?

Since you specified that the language is "C", it's


worth pointing out that the Ansi standard guarantees


that the implementation will include a "qsort" function.





All you need to do is write the simple comparison


function which is passed to qsort, and you're done.





I copied the following (including the little test program)


directly from the qsort man page:





#include %26lt;stdlib.h%26gt;


#include %26lt;stdio.h%26gt;





static int


intcompare(const void *p1, const void *p2)


{


  int i = *((int *)p1);


  int j = *((int *)p2);





  if (i %26gt; j)


    return (1);


  if (i %26lt; j)


    return (-1);


  return (0);


}





int


main()


{


  int i;


  int a[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };


  size_t nelems = sizeof (a) / sizeof (int);





  qsort((void *)a, nelems, sizeof (int), intcompare);





  for (i = 0; i %26lt; nelems; i++)


    (void) printf("%d ", a[i]);





  (void) printf("\n");


  return (0);


}








See the references for the man page as well as the


source from the OpenSolaris site.

Write a C program for sorting numbers.?
... don't forget to print the numbers
Reply:void bubbleSort_flag(int a[], int n)


{


int i, j, temp, flag;


for(i=n-1; i%26gt;0; i--)


{


flag = 1;


for(j=0; i%26gt;j; j++)


{


if(a[j]%26gt;a[j+1])


{


flag = 0;


temp = a[j];


a[j] = a[j+1];


a[j+1] = temp;


}


}


//out this block when flag is true


//i.e. inner loop performed no swaps, so the list is already sorted


if(flag)


break;


}


}
Reply:To me, this is the best source of sorting in Java code:





http://www.cs.ubc.ca/~harrison/Java/sort...





You can easily change it to C, given some patience.





The one I use most is QuickSort by Gosling
Reply:For the sorting of numbers, the best sorting algorithm is often times the bucket-sort or radix-sort algorithm. The general idea of this algorithm is to place different numbers into respective "buckets" based on the different digits of the number starting from the highest digit. The wiki for it can be found here -





http://en.wikipedia.org/wiki/Radix_sort


No comments:

Post a Comment