I am trying to figure out how to sort a given array without using PHP's built in sort functions. I know that this is much harder but I am not allowed to use the sort functions. I know I have to use loops just not exactly sure how to go about it.
-
sounds like homework? What are the values? Please edit your question and add some example dataPhill Pafford– Phill Pafford2011-11-07 17:35:48 +00:00Commented Nov 7, 2011 at 17:35
-
4Might as well start with the simplest sort function there is: en.wikipedia.org/wiki/Bubble_sortonit– onit2011-11-07 17:36:19 +00:00Commented Nov 7, 2011 at 17:36
-
Is this a homework? If so, you should say that.Nicolás Ozimica– Nicolás Ozimica2011-11-07 17:36:22 +00:00Commented Nov 7, 2011 at 17:36
-
Since you say you're "not allowed" to use sort functions, I'm assuming this is some sort of homework assignment. Others might be willing to give you code, but my suggestion would be to try it yourself. You'll learn more. I will give you a hint, though. Imagine how you look through a dictionary or phone book. Does the word come before or after the page you're on? If so, move it up in the list. If not, move it down.Jemaclus– Jemaclus2011-11-07 17:36:26 +00:00Commented Nov 7, 2011 at 17:36
-
You could use the good old bubble-sort: phptutorialonline.com/php-bubble-sort.aspxQuasdunk– Quasdunk2011-11-07 17:36:30 +00:00Commented Nov 7, 2011 at 17:36
3 Answers
Here is a simple sort to get you started: http://en.wikipedia.org/wiki/Bubble_sort
If you want the names of different sorts: http://en.wikipedia.org/wiki/Sorting_algorithm
Comments
You might want to take this approach:
- Create a new, empty array.
- Inside a
whileloop, repeatedly look through the existing array. At each step, look for the next array element to be chosen. - When you identify it, delete it from the old array and add it to the new array.
- Repeat until the original array is empty.
- Return your new array.
Since this sounds like a homework exercise, I leave it to you to do the work of turning this outline into working code.
Comments
Might as well look into the fastest sort right away: Quicksort
As it seems like homework, make sure you implement it yourself and really understand what's happening (also make sure you understand why it's so fast and efficient). It's also a good introduction to divide-and-conquer approaches to problem solving.
The wikipedia pseudo code should help you get started, good luck!