netjunky

Sorting array

Nov 29th, 2010
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. #define DEBUG 0
  5.  
  6. void sortArray( int *a, int length );
  7. void printArray( int *a, int length );
  8. void arraySmallestValue( int value, int index );
  9.  
  10. int main( int argc, char **argv )
  11. {  
  12.     int a[5] = {3, 5, 1, 4, 2};
  13.    
  14.     sortArray( a, 5 );
  15.    
  16.     return 0;
  17. }
  18.  
  19. void sortArray( int *a, int length )
  20. {
  21.     int i = 0;
  22.     int smallest = 0;
  23.     int index = 0;
  24.     int replaceInd = 0;
  25.     int replaceValue = 0;
  26.    
  27.     printArray( a, length ); // Starting array
  28.    
  29.     if ( 0 < length )
  30.     {
  31.         smallest = a[ 0 ];
  32.     }
  33.    
  34.     arraySmallestValue( smallest, replaceInd );
  35.    
  36.     while ( ( length - 1 ) != replaceInd )
  37.     {  
  38.         for ( i = replaceInd; i < length; i++ )
  39.         {
  40.             if ( a[ i ] < smallest )
  41.             {
  42.                 smallest = a[ i ];
  43.                 index = i;
  44.             }
  45.         }
  46.        
  47.         if ( a[ replaceInd ] != smallest )
  48.         {
  49.             replaceValue = a[ replaceInd ];
  50.             a[ replaceInd ] = smallest;
  51.             a[ index ] = replaceValue;
  52.         }
  53.        
  54.         replaceInd++;
  55.        
  56.         smallest = a[ replaceInd ];
  57.        
  58.         // DEBUGing part
  59.         printArray( a, length );
  60.         arraySmallestValue( smallest, replaceInd );
  61.     }
  62. }
  63.  
  64. void printArray( int *a, int length )
  65. {
  66.     int i = 0;
  67.    
  68.     printf( "Here is array:\n" );
  69.    
  70.     for ( i = 0; i < length; i++ )
  71.     {
  72.         printf( "%d\t=>\t%d\n", i, a[ i ] );
  73.     }
  74. }
  75.  
  76. void arraySmallestValue( int value, int index )
  77. {
  78.     printf( "We start with number %d and it is on index %d\n\n", value, index );
  79. }
Add Comment
Please, Sign In to add comment