Return to Snippet

Revision: 2000
at December 11, 2006 12:43 by section31


Initial Code
// convert associative array to 2d array
function arr_convert_2d($arr) {
	$tmp_arr = array();
	foreach ($arr as $k => $v) {
		$tmp_arr[] = array('index' => $k, 'value' => $v);
	}
	
	return $tmp_arr;
}

// convert 2d associative array to 1d array
function arr_convert_1d($arr) {
	$tmp_arr = array();
	foreach ($arr as $v) {
		$tmp_arr[$v['index']] = $v['value'];
	}

	return $tmp_arr;
}

function assoc_quicksort($arr)
{
	if (!count($arr)) return $arr;

	$pivot = $arr[0];
	$left = $right = array();

	for($i = 1; $i < count($arr); $i++) {
		if($arr[$i]['value'] <= $pivot['value']) {
			$left[] = $arr[$i];
		}
		else {
			$right[] = $arr[$i];
		}
	}

	return array_merge(assoc_quicksort($left), array($pivot), assoc_quicksort($right));
}

$qsort_assoc_arr = arr_convert_1d(assoc_quicksort(arr_convert_2d($changed_arr)));

Initial URL

                                

Initial Description

                                

Initial Title
Associative Quick Sort

Initial Tags

                                

Initial Language
PHP