How to bubble sort 2d array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • deizi23
    New Member
    • Nov 2015
    • 6

    How to bubble sort 2d array?

    I have to sort 2d array
    $
    Code:
    items = array(
    		 array(15, 16, 8, 1),
    		 array(2, 3, 4, 7),
    		 array(9, 11, 19, 6,)
    );
     with bubble sort ant to get something like this
    
    1,2,3,4
    6,7,8,9
    11,15,16,19
    I can't find anywhere bubble sort for multiple arrays.
    Can you help me?
    Last edited by zmbd; Nov 29 '15, 03:57 PM. Reason: [z{please use the [CODE/] formatting tool for scripts}]
  • jaseel97
    New Member
    • Feb 2015
    • 16

    #2
    You could store all the elements of the 2D array into a 1D array, sort that array, and update the values
    Of the 2D array with values from the sorted 1D array.
    Is it necessary that you have to perform bubble sort on the 2D array as a whole?

    Comment

    • maNdy3
      New Member
      • Nov 2015
      • 5

      #3
      Seems like me and Deizi share the same assignments. Yes, it is necessary to bubble sort it as a whole.
      I`ve already done it the easy way - foreach to create a 1d array out of the 2d, then bubble sort, than array_chunk to make it 2d again.
      Now I`m trying to do it without changing it.
      Here is what I have so far :
      Code:
      $array = [
      		[5, 8, 7, 6],
      		[1, 15, 10, 9],
      		[2, 13, 3, 4],
      		[11, 16, 12, 14],
      ];
      
      $len = count($array);
      for ($all = 0; $all < $len*$len; $all++) {
      	for ($k = 0; $k < $len; $k++) {
      		for ($i = 0; $i < $len; $i++) {
      			for ($j = 0; $j < $len -1; $j++) {
      				if ($array[$k][$j] > $array[$k][$j + 1]) {
      					$helperVar = $array[$k][$j + 1];
      					$array[$k][$j + 1] = $array[$k][$j];
      					$array[$k][$j] = $helperVar;
      					$hasSwap = true;
      				}
      			}
      		}
      	}
      }
      var_dump($array);
      It sorts the cols, but that`s it ... Seems like I can`t make the first "for" work.

      Comment

      Working...