冒泡排序
function bubbleSort($arr)
{
$count = count($arr);
for ($i = 0; $i < $count;$i++){
for ($j = 0;$j < $count -1 - $i;$j++){
if ($arr[$j] > $arr[$j+1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
return $arr;
}
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@20,@40,@10,@50,@0, nil];
NSUInteger count = [arr count];
for (NSUInteger i = 0; i < count; i++) {
for (NSUInteger j = 0; j < count - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
[arr exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
}
快速排序
function quickSort($arr)
{
$count = count($arr);
if ($arr <= 1) {
return $arr;
}
$point = $arr[0];
$left = [];
$right = [];
for ($i = 1; $i < $count; $i++) {
if ($arr[$i] < $point) {
$left[] = $arr[$i];
} else {
$right[] = $arr[$i];
}
}
$left = quickSort($left);
$right = quickSort($right);
return array_merge($left, [$point], $right);
}
网友评论