排序算法:插入排序算法 PHP 版

思路:每次插入数据时均和前面的数据做比较,一直找到合适的插入位置。

id < $data[$i - 1]->id) {
			$j = $i - 1;
			$x = $data[$i]->id;
			$obj = $data[$i];
			while ($j > -1 && $x < @$data[$j]->id) {
				$data[$j + 1] = $data[$j];
				$j--;
			}
			$data[$j + 1] = $obj;
		}
	}
}

(function () {

	$person = new Person();
	$index = [
		'23' => '勺颠颠',
		'65' => '老油条',
		'21' => '烧包谷',
		'9' => '烧耳块',
		'4' => '肥嘟嘟',
		'7' => '霉戳戳',
		'32' => '一坨肉',
		'6' => '老扎哇'
	];
	$data = [];
	foreach ($index as $k => $v) {
		$obj = clone $person;
		$obj->id = $k;
		$obj->data = $v;
		$data[] = $obj;
	}
	insertSort($data, 8);

	var_dump($data);

})();

 

你可能感兴趣的:(php)