fork(1) download
  1. //Fig. 6.15: fig06_15.c
  2. //Sorting an array's value in ascending order.
  3. #include <stdio.h>
  4. #define SIZE 10
  5.  
  6. // function main begins program execution
  7. int main()
  8. {
  9. // initialize a
  10. int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
  11. int pass; // passes counter
  12. size_t i; // comparisons counter
  13. int hold; // temporary-location used to swap array elements
  14.  
  15. puts("Data items in original order");
  16.  
  17. //output original array
  18. for( i = 0; i < SIZE; ++i) {
  19. printf("%4d", a[ i ]);
  20. }// end for
  21.  
  22. //bubble sort
  23. //loop to control number of passes
  24. for( pass = 1; pass < SIZE; ++pass ) {
  25.  
  26. //loop to control number of comparisons per pass
  27. for( i = 0; i <SIZE - 1; ++i){
  28.  
  29. //compare adjacent elements and swap them if first
  30. //element is greater than second element
  31. if ( a[ i ] > a[ i + 1 ] ){
  32.  
  33. hold = a[ i ];
  34. a[ i ] = a[ i + 1 ];
  35. a[ i + 1 ] = hold;
  36. }//end if
  37. }//end inner for
  38. }//end outer for
  39.  
  40. puts("\nData items in ascending order");
  41.  
  42. //output sorted array
  43. for( i = 0; i < SIZE; ++i ) {
  44. printf( "%4d", a[ i ] );
  45. }//end for
  46.  
  47. puts("");
  48. }//end main
Runtime error #stdin #stdout 0s 2008KB
stdin
Standard input is empty
stdout
Data items in original order
   2   6   4   8  10  12  89  68  45  37
Data items in ascending order
   2   4   6   8  10  12  37  45  68  89