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

· 10년 전 · 1631

<?

// 퀵 정렬(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,788
10년 전 조회 1,823
10년 전 조회 1,926
10년 전 조회 1,770
10년 전 조회 1,911
10년 전 조회 1,671
10년 전 조회 1,781
10년 전 조회 1,560
10년 전 조회 1,809
10년 전 조회 1,594
10년 전 조회 1,658
10년 전 조회 1,755
10년 전 조회 1,647
10년 전 조회 1,686
10년 전 조회 1,636
10년 전 조회 2,045
10년 전 조회 2,054
10년 전 조회 2,049
10년 전 조회 2,007
10년 전 조회 1,786
10년 전 조회 1,913
10년 전 조회 2,062
10년 전 조회 1,766
10년 전 조회 2,063
10년 전 조회 2,020
10년 전 조회 2,408
10년 전 조회 2,022
10년 전 조회 2,233
10년 전 조회 1,846
10년 전 조회 2,006
10년 전 조회 1,689
10년 전 조회 1,777
10년 전 조회 1,804
10년 전 조회 1,816
10년 전 조회 1,979
10년 전 조회 1,747
10년 전 조회 1,775
10년 전 조회 1,793
10년 전 조회 1,693
10년 전 조회 1,745
10년 전 조회 1,553
10년 전 조회 1,628
10년 전 조회 1,542
10년 전 조회 1,709
10년 전 조회 1,649
10년 전 조회 2,122
10년 전 조회 1,597
10년 전 조회 1,555
10년 전 조회 1,826
10년 전 조회 1,632
10년 전 조회 1,583
10년 전 조회 1,596
10년 전 조회 1,561
10년 전 조회 1,475
10년 전 조회 1,455
10년 전 조회 1,570
10년 전 조회 1,539
10년 전 조회 1,496
10년 전 조회 1,391
10년 전 조회 1,458
10년 전 조회 1,501
10년 전 조회 1,470
10년 전 조회 1,540
10년 전 조회 1,508
10년 전 조회 1,477
10년 전 조회 1,474
10년 전 조회 1,517
10년 전 조회 1,490
10년 전 조회 1,574
10년 전 조회 1,482
10년 전 조회 1,435
10년 전 조회 1,408
10년 전 조회 1,432
10년 전 조회 1,458
10년 전 조회 1,441
10년 전 조회 1,471
10년 전 조회 1,411
10년 전 조회 1,481
10년 전 조회 1,428
10년 전 조회 1,510
10년 전 조회 1,597
10년 전 조회 1,580
10년 전 조회 1,504
10년 전 조회 1,425
10년 전 조회 1,570
10년 전 조회 1,466
10년 전 조회 1,502
10년 전 조회 1,443
10년 전 조회 1,435
10년 전 조회 1,422
10년 전 조회 1,449
10년 전 조회 1,553
10년 전 조회 1,474
10년 전 조회 1,560
10년 전 조회 1,464
10년 전 조회 1,524
10년 전 조회 1,515
10년 전 조회 1,574
10년 전 조회 1,636
10년 전 조회 1,708