Hello, I am new to php and am trying to do the following task.

Complete the following PHP script so that it prints the numbers, given in a form, in a specific order. The script should organize the numbers from largest to the smallest and from smallest to largest and print both of these number strings on screen. The points are sent to the script as a character string, where points are separated with comma (e.g. 4,5,2). Points are divided into an array with the explode-function. Using the sort-function is not allowed. Do the organizing with a for-statement. Incomplete program:

<?php

$numberstring = $_GET['numberstring'];

$array = explode(',',$numberstring);



echo "Order in the beginning: $numberstring\n";



// Your code here and only here



echo "Largest to smallest: $largest_smallest\n";

echo "Smallest to largest: $smallest_largest\n";

?>

First I tried it if it works with the following straight forward code:

$largest_smallest=rsort($numberstring );
$smallest_largest=sort($numberstring );

And it gave me the following error:

Order in the beginning: 4,7,-2,0,6

Warning: rsort() expects parameter 1 to be array, string given in /tmp/K2U5XgShJ9/1/.php on line 9

Warning: sort() expects parameter 1 to be array, string given in /tmp/K2U5XgShJ9/1/.php on line 10
Largest to smallest:
Smallest to largest:

So can any one help me why there is an error and also according to the assignment I am supposed to do it with for statement. what is the equivalent way of sort() or rsort() doing this? thank you so much!

Example output:

Order in the beginning: 4,7,-2,0,6
Largest to smallest: 7,6,4,0,-2
Smallest to largest: -2,0,4,6,7

    First of all, welcome to the forums; please note the FAQs, including the markup tags that allow you to mark up your post to make it more readable.

    danielki wrote:

    Warning: rsort() expects parameter 1 to be array, string given in /tmp/K2U5XgShJ9/1/.php on line 9

    Well, that's because you're trying to sort [font=monospace]$numberstring[/font], not [font=monospace]$array[/font].

    As for the rest of it: you don't think we're going to do your homework for you, do you?

      danielki;11039141 wrote:

      Using the sort-function is not allowed.

      lol.

      Use [man]rsort/man and [man]array_reverse/man

        I could be wrong, but it clearly says that using the sort function is not allowed and that one should be using a for loop to do the work. In reality, one would of course use the sort function. Sounds to me like someone isn't paying attention in class.

          TBH, I don't think I know how to complete a sort using a for loop.

            Derokorian;11039227 wrote:

            TBH, I don't think I know how to complete a sort using a for loop.

            Without class notes, it would be a total pain in the ass. Wikipedia has some decent pseudo for Quicksort. There's also Bubble Sort.

              sneakyimp;11039231 wrote:

              Without class notes, it would be a total pain in the ass. Wikipedia has some decent pseudo for Quicksort. There's also Bubble Sort.

              Yes I know about quicksort and insertionsort from challenges on hacker rank. I've not heard of bubble sort before though, interesting read.

                Should be doable, not too neatly, with placeholders, unset(), and max() or min(), don't you think?

                  dalecosp;11039245 wrote:

                  Should be doable, not too neatly, with placeholders, unset(), and max() or min(), don't you think?

                  I'm thinking [man]min[/man] and [man]max[/man] would be especially helpful. Loop through the original array and keep checking max, constructing a new array by peeling off the value returned by it and adding it to the other array. You would probably also need [man]array_search[/man] to find out which array element to [man]array_slice[/man] out of the original array.

                    sneakyimp;11039247 wrote:

                    I'm thinking [man]min[/man] and [man]max[/man] would be especially helpful. Loop through the original array and keep checking max, constructing a new array by peeling off the value returned by it and adding it to the other array. You would probably also need [man]array_search[/man] to find out which array element to [man]array_slice[/man] out of the original array.

                    You could, possibly, just unset() it in the same operation/conditional. I've not tried to implement it, but it's where I'd start.

                      Derokorian wrote:

                      TBH, I don't think I know how to complete a sort using a for loop.

                      Trying to sort an arbitrary array with only a single for loop -- with no other loops or recursion -- would indeed be quite difficult, methinks 🙂 Even if say, counting sort were applicable, I think you still need more than just one for loop.

                      My guess is that danielki's instructor merely intended for the implementation of a sorting algorithm, with at least one for loop to be used, but with no constraints as to which sorting algorithm to implement. I see that quicksort and bubble sort have been mentioned, but I suspect that quicksort would be beyond danielki's current programming abilities. I think insertion sort or bubble sort would be feasible.

                      sneakyimp wrote:

                      Loop through the original array and keep checking max, constructing a new array by peeling off the value returned by it and adding it to the other array.

                      That would be selection sort, except one that is not in-place. An in-place version might be feasible for danielki too, except that I don't think max (or min) can be used since one would swap the max element with the current end of the unsorted range, so we need the position, not just the value.

                        A Bogosort implementation with the constraint that it uses precisely one for-loop.

                        $length = count($array);
                        for($i = 0; $i < $length; ++$i)
                        {
                        	if($i == 0)
                        	{
                        		shuffle($array);
                        	}
                        	elseif($array[$i - 1] > $array[$i])
                        	{
                        		$i = -1;
                        	}
                        	elseif($i == $length)
                        	{
                        		break;
                        	}
                        }
                        

                        Note: contains one deliberate bug and one unjustified assumption.

                          shuffle is a sort function in this context.

                            laserlight;11039311 wrote:

                            Trying to sort an arbitrary array with only a single for loop -- with no other loops or recursion -- would indeed be quite difficult, methinks 🙂 Even if say, counting sort were applicable, I think you still need more than just one for loop.

                            That sounds about right to me, and is probably one of the things this problem assignment is supposed to teach. They probably mentioned something like this in class...

                            laserlight;11039311 wrote:

                            My guess is that danielki's instructor merely intended for the implementation of a sorting algorithm, with at least one for loop to be used, but with no constraints as to which sorting algorithm to implement. I see that quicksort and bubble sort have been mentioned, but I suspect that quicksort would be beyond danielki's current programming abilities. I think insertion sort or bubble sort would be feasible.

                            I remember sitting in the CS lab in college (I didn't even own a computer when I was getting my CS degree) trying to do the sorting algorithm homework. I do remember bubble sort but not insertion sort (I was also pretty bad about going to class). I vaguely recall that quicksort was the culmination of the sorting lesson. I also remember the profs of one big class setting up a contest to see who could sort a collection of numbers the fastest. One of the students wrote a Bucket Sort program that ran faster than the profs' algorithm. I don't remember who that guy was but he was smart enough to ask how many numbers had to be sorted and how much RAM the machine would have, etc. I was lucky I could get my code to even run.

                            laserlight;11039311 wrote:

                            That would be selection sort, except one that is not in-place. An in-place version might be feasible for danielki too, except that I don't think max (or min) can be used since one would swap the max element with the current end of the unsorted range, so we need the position, not just the value.

                            I wasn't thinking so much about swapping elements within an array but rather building an entirely separate array by pulling out the biggest/smallest element from the original array one at a time. You could use [man]max[/man] to find the value of the biggest element, [man]array_search[/man] to locate its index, and [man]array_slice[/man] to extract it. This is probably not very efficient, but the code would be pretty compact I think.

                              sneakyimp wrote:

                              I wasn't thinking so much about swapping elements within an array but rather building an entirely separate array by pulling out the biggest/smallest element from the original array one at a time.

                              That is why I observed that your suggestion "would be selection sort, except one that is not in-place".

                                laserlight;11039325 wrote:

                                That is why I observed that your suggestion "would be selection sort, except one that is not in-place".

                                Of course...sorry. I've not been paying very close attention. Your comments are, as always, very helpful and insightful.

                                  laserlight wrote:

                                  shuffle is a sort function in this context.

                                  You're just saying that to make me have to encode a more complicated state machine into the loop counter, aren't you? 🙂

                                    Weedpacket wrote:

                                    You're just saying that to make me have to encode a more complicated state machine into the loop counter, aren't you?

                                    Well... if you do that, then you're just fulfilling the first part of my observation, i.e., that it "would indeed be quite difficult". As it stands, your code makes it look too easy by breaking the spirit of the "using the sort-function is not allowed" rule 😉

                                      laserlight;11039335 wrote:

                                      Well... if you do that, then you're just fulfilling the first part of my observation, i.e., that it "would indeed be quite difficult". As it stands, your code makes it look too easy by breaking the spirit of the "using the sort-function is not allowed" rule 😉

                                      However, the definition of bogosort doesn't specify the shuffling method to use, assuming that it is already supplied.

                                      $length = count($array);
                                      
                                      for($i = 0; $i < 2 * $length - 1; $i += 2)
                                      {
                                      	if(!($i & 1))
                                      	{
                                      		$l = mt_rand(0, $i / 2);
                                      		$t = $array[$i / 2];
                                      		$array[$i / 2] = $array[$l];
                                      		$array[$l] = $t;
                                      		if($i / 2 == $length - 1)
                                      		{
                                      			$i = -1;
                                      		}
                                      	}
                                      	elseif($array[($i - 1) / 2] > $array[($i + 1) / 2])
                                      	{
                                      		$i = -2;
                                      	}
                                      }
                                      
                                        Write a Reply...