[알고리즘]퀵 정렬(Quick Sort)

· 10년 전 · 1627

<?

// 퀵 정렬(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);

?>

|
댓글을 작성하시려면 로그인이 필요합니다.

프로그램

+
제목 글쓴이 날짜 조회
10년 전 조회 1,780
10년 전 조회 1,813
10년 전 조회 1,924
10년 전 조회 1,770
10년 전 조회 1,902
10년 전 조회 1,670
10년 전 조회 1,779
10년 전 조회 1,560
10년 전 조회 1,800
10년 전 조회 1,587
10년 전 조회 1,652
10년 전 조회 1,752
10년 전 조회 1,644
10년 전 조회 1,677
10년 전 조회 1,632
10년 전 조회 2,041
10년 전 조회 2,048
10년 전 조회 2,045
10년 전 조회 2,002
10년 전 조회 1,783
10년 전 조회 1,907
10년 전 조회 2,062
10년 전 조회 1,766
10년 전 조회 2,056
10년 전 조회 2,011
10년 전 조회 2,401
10년 전 조회 2,017
10년 전 조회 2,225
10년 전 조회 1,838
10년 전 조회 1,999
10년 전 조회 1,686
10년 전 조회 1,772
10년 전 조회 1,804
10년 전 조회 1,814
10년 전 조회 1,978
10년 전 조회 1,745
10년 전 조회 1,773
10년 전 조회 1,786
10년 전 조회 1,688
10년 전 조회 1,743
10년 전 조회 1,550
10년 전 조회 1,624
10년 전 조회 1,538
10년 전 조회 1,705
10년 전 조회 1,643
10년 전 조회 2,120
10년 전 조회 1,591
10년 전 조회 1,551
10년 전 조회 1,822
10년 전 조회 1,628
10년 전 조회 1,579
10년 전 조회 1,591
10년 전 조회 1,557
10년 전 조회 1,472
10년 전 조회 1,454
10년 전 조회 1,565
10년 전 조회 1,532
10년 전 조회 1,494
10년 전 조회 1,386
10년 전 조회 1,453
10년 전 조회 1,495
10년 전 조회 1,466
10년 전 조회 1,536
10년 전 조회 1,504
10년 전 조회 1,475
10년 전 조회 1,471
10년 전 조회 1,514
10년 전 조회 1,486
10년 전 조회 1,569
10년 전 조회 1,476
10년 전 조회 1,427
10년 전 조회 1,405
10년 전 조회 1,431
10년 전 조회 1,456
10년 전 조회 1,439
10년 전 조회 1,468
10년 전 조회 1,406
10년 전 조회 1,479
10년 전 조회 1,423
10년 전 조회 1,505
10년 전 조회 1,596
10년 전 조회 1,574
10년 전 조회 1,502
10년 전 조회 1,421
10년 전 조회 1,566
10년 전 조회 1,464
10년 전 조회 1,498
10년 전 조회 1,442
10년 전 조회 1,433
10년 전 조회 1,418
10년 전 조회 1,448
10년 전 조회 1,550
10년 전 조회 1,471
10년 전 조회 1,554
10년 전 조회 1,462
10년 전 조회 1,523
10년 전 조회 1,513
10년 전 조회 1,571
10년 전 조회 1,636
10년 전 조회 1,704