ccplusplus.com
Learn C, C++ Concepts
Saturday, September 10, 2011
sorting an array in c
/****************************************************** * File : sort-numbers.c * Author : Saurabh Gupta * Desc : sort a given numbers from user * Source : http://saurabhgupta0527.blogspot.com/ * Created : PM 10:55 10 September 2011 * Note : change NUM_ELEM_TO_SORT to number of * values to sort. *****************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define NUM_ELEM_TO_SORT 5 void sort(int m, int x[]); int main() { int i, nNumberToSort; int NumbersToSort[NUM_ELEM_TO_SORT]; printf ("Enter %d values to sort\n", NUM_ELEM_TO_SORT); for (i = 0; i <NUM_ELEM_TO_SORT; i++) { scanf ("%d", &nNumberToSort); NumbersToSort[i] = nNumberToSort; } printf("Numbers before sorting\n"); for(i=0; i<5; i++) { printf("%4d", NumbersToSort[i]); } printf("\n\n"); sort(5,NumbersToSort); printf("Numbers after sorting\n"); for(i=0; i<5; i++) printf("%4d", NumbersToSort[i]); printf("\n"); return 0; } /* * this function will sort all the input values */ void sort(int m, int x[]) { int i, j, temp; for(i=1; i<=m-1; i++) { for(j=1;j<=m-1;j++) { if(x[j-1]>=x[j]) { temp=x[j-1]; x[j-1]=x[j]; x[j]=temp; } } } } /* * OUTPUT * [sgupta@rhel54x64 c]$ gcc sort-numbers.c -o sort-numbers [sgupta@rhel54x64 c]$ ./sort-numbers Enter 5 values to sort 10 32 4 1 99 Numbers before sorting 10 32 4 1 99 Numbers after sorting 1 4 10 32 99 */
See also
Other popular tricky C Sample Codes and language Concept
.
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment