Results 1 to 5 of 5

Thread: insertion sort

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default insertion sort

    i am trying to write this algorithm in php but the output doesnt sort the array from small to large value like its supposed to. the algorithm is taken from a text book but my syntax might be wrong. can anyone lend a hand please

    PHP Code:
    <?php
    $arr 
    = array( 4323242899982142322212);
    $j 0;
     
    for( 
    $j$j $arr.length$j++ )
    {
            
    $key $arr[$j];
            
    $i $j 1;
     
            while( 
    $i > -&& $arr[$i] > $key )
            {
                    
    $arr[$i 1] = $arr[$i];
                    
    $i $i 1
            }
     
            
    $arr[$i 1] = $key;
            
    }
    print_r($arr);

    ?>

  2. #2
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    nm
    Code:
    count($arr)

  3. #3
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    why does the output look like this?
    Code:
    Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 21 [5] => 22 [6] => 28 [7] => 423 [8] => 821 [9] => 999 [10] => 2324 )
    how can i get rid of the array index and "=>" symbol

  4. #4
    Join Date
    May 2007
    Location
    Boston,ma
    Posts
    2,127
    Thanks
    173
    Thanked 207 Times in 205 Posts

    Default

    The print_r does that you'll need to use a foreach loop.

    PHP Code:
    <?php
    $arr 
    = array( 4323242899982142322212);
    $j 0;
     
    for( 
    $j$j $arr.length$j++ )
    {
            
    $key $arr[$j];
            
    $i $j 1;
     
            while( 
    $i > -&& $arr[$i] > $key )
            {
                    
    $arr[$i 1] = $arr[$i];
                    
    $i $i 1
            }
     
            
    $arr[$i 1] = $key;
            
    }
    foreach (
    $arr as $value) {
        echo 
    "$value<br />\n";
    }
    ?>
    Corrections to my coding/thoughts welcome.

  5. #5
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    i see, thank you

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •