-2

I got the following task, and unfortunately I have no idea how to solve it.

You have the following function already implemented:

function array_swap(&$ar,$j) { ... } // changes element at position $j with element at position 0
/*
 * Example:
 * $ar=array(3,1,5);
 * array_swap($ar, 2); // change element at position 2 with element at position 0
 * result is array(5,1,3);
*/

1 You must use array_swap function

2 You can compare elements in the array

3 You can use any loops (for, foreach, while, etc)

4 The task is to sort the array ascending

Can someone give me help, ideas how to implement this? Maybe an algorithm enough, I hope so I can code. :) This is an algorithm question, and I checked the existing algorithms before, but didn't found any similar.

  • 1
    ..can you explain the : "..The task is to sort the array ascending..." ? If you swap two elements pos. 4 with pos. 0 for example and then sort the array the result will always be the same – Milan Jan 12 '17 at 23:50
  • 1
    Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – Icarus Jan 12 '17 at 23:58
  • 2
    @Milan it's probably an algorithm question where you are required to use the given function to figure out how to sort an array. To the OP, what have you actually tried coming up with? – georaldc Jan 13 '17 at 00:02

1 Answers1

0

One tip to solving this is to use the array_swap function twice: First is to place the highest value found so far into the first index, then moving it to the end of the array. Now that you have the highest value in the right place, you can move down 1 index. You just have to find the next highest value below your previous highest one and do the double swap again. Repeat until you reach the beginning of the array.

The above is an O(n^2) solution though, so there's probably more effective solutions out there.

georaldc
  • 1,880
  • 16
  • 24
  • Thank you very much! This gave me the help to write the code to produce a solution. Here is the code I've written: https://codeshare.io/GbvnnO – Hagrid_FBI Jan 13 '17 at 14:51
  • That will work I guess, but you can get away without using a second array, and without using an array_search function. You just have to keep track of the current highest value and the index you need to insert it into next – georaldc Jan 13 '17 at 15:27
  • Here's an algorithm that will sort the array in place without using additional storage, and without using any other built in functions that would add overhead. It's in javascript, but it should be easy to translate over to php. Added some comments to explain some of the lines. https://jsfiddle.net/georaldc/nmd8h2f8/ – georaldc Jan 13 '17 at 17:21