[알고리즘]퀵 정렬(Quick Sort)
링크
http://terms.naver.com/entry.nhn?docId=2270444&cid=51173&categoryId=51173 (35) https://ko.wikipedia.org/wiki/%ED%80%B5_%EC%A0%95%EB%A0%AC (29)<?
// 퀵 정렬(Quick Sort)
function Swap(&$arr, $idx1, $idx2) {
$temp = $arr[$idx1];
$arr[$idx1] = $arr[$idx2];
$arr[$idx2] = $temp;
}
// 중간값 찾기
function MedianOfThree($arr, $left, $right) {
$samples = array($left, floor(($left+$right)/2), $right);
if ($arr[$samples[0]] > $arr[$samples[1]])
Swap($samples, 0, 1);
if ($arr[$samples[1]] > $arr[$samples[2]])
Swap($samples, 1, 2);
if ($arr[$samples[0]] > $arr[$samples[1]])
Swap($samples, 0, 1);
return $samples[1];
}
function Partition(&$arr, $left, $right) {
$pIdx = MedianOfThree($arr, $left, $right); // 중간값으로 피벗 선택
$pivot = $arr[$pIdx];
$low = $left + 1;
$high = $right;
Swap($arr, $left, $pIdx); // 피벗을 가장 왼쪽으로 이동
while ($low <= $high) { // 교차되지 않을 때까지 반복
// 피벗보다 큰 값을 찾는 과정
while ($low <= $right && $pivot >= $arr[$low])
$low++;
// 피벗보다 작은 값을 찾는 과정
while ($high >= ($left+1) && $pivot <= $arr[$high])
$high--;
// 교차되지 않는 상태라면 Swap 실행
if ($low <= $high)
Swap($arr, $low, $high);
}
Swap($arr, $left, $high); // 피벗과 high 가 가리키는 대상 교환
return $high; // 옮겨진 피벗의 위치정보 교환
}
function QuickSort(&$arr, $left, $right) {
if ($left < $right) {
$pivot = Partition($arr, $left, $right);
QuickSort($arr, $left, $pivot-1);
QuickSort($arr, $pivot+1, $right);
}
}
$arr = array(3, 2, 4, 1, 7, 6, 5);
$len = count($arr);
QuickSort($arr, 0, $len-1);
print_r($arr);
?>
게시판 목록
토크
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 3510 | 7년 전 | 2782 | ||
| 3509 | 8년 전 | 3598 | ||
| 3508 |
좋은사람우유
|
8년 전 | 4879 | |
| 3507 | 8년 전 | 5057 | ||
| 3506 | 8년 전 | 3440 | ||
| 3505 | 8년 전 | 3011 | ||
| 3504 | 8년 전 | 4028 | ||
| 3503 | 8년 전 | 3782 | ||
| 3502 | 8년 전 | 4235 | ||
| 3501 | 8년 전 | 2972 | ||
| 3500 |
|
8년 전 | 2752 | |
| 3499 |
|
8년 전 | 3195 | |
| 3498 |
|
8년 전 | 2784 | |
| 3497 | 8년 전 | 2951 | ||
| 3496 | 8년 전 | 2999 | ||
| 3495 |
|
8년 전 | 1325 | |
| 3494 |
|
8년 전 | 2432 | |
| 3493 | 8년 전 | 2085 | ||
| 3492 |
체리맛쿠키
|
8년 전 | 2557 | |
| 3491 |
제임스딘님
|
8년 전 | 1872 | |
| 3490 | 8년 전 | 1718 | ||
| 3489 |
tiadk
|
8년 전 | 3278 | |
| 3488 |
동팔이22
|
8년 전 | 2217 | |
| 3487 |
초등학교학생
|
8년 전 | 1821 | |
| 3486 |
|
8년 전 | 3349 | |
| 3485 | 8년 전 | 2468 | ||
| 3484 | 8년 전 | 2614 | ||
| 3483 | 8년 전 | 4558 | ||
| 3482 | 8년 전 | 9172 | ||
| 3481 | 8년 전 | 3676 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기