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

· 10년 전 · 1267

<?

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

?>

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

프로그램

+
제목 글쓴이 날짜 조회
9년 전 조회 1,446
9년 전 조회 1,441
9년 전 조회 1,554
9년 전 조회 1,425
10년 전 조회 1,535
10년 전 조회 1,374
10년 전 조회 1,444
10년 전 조회 1,260
10년 전 조회 1,496
10년 전 조회 1,309
10년 전 조회 1,319
10년 전 조회 1,419
10년 전 조회 1,346
10년 전 조회 1,359
10년 전 조회 1,283
10년 전 조회 1,696
10년 전 조회 1,740
10년 전 조회 1,714
10년 전 조회 1,650
10년 전 조회 1,443
10년 전 조회 1,582
10년 전 조회 1,726
10년 전 조회 1,412
10년 전 조회 1,720
10년 전 조회 1,695
10년 전 조회 2,074
10년 전 조회 1,670
10년 전 조회 1,895
10년 전 조회 1,522
10년 전 조회 1,640
10년 전 조회 1,373
10년 전 조회 1,424
10년 전 조회 1,496
10년 전 조회 1,494
10년 전 조회 1,625
10년 전 조회 1,404
10년 전 조회 1,430
10년 전 조회 1,387
10년 전 조회 1,347
10년 전 조회 1,406
10년 전 조회 1,238
10년 전 조회 1,290
10년 전 조회 1,200
10년 전 조회 1,341
10년 전 조회 1,286
10년 전 조회 1,764
10년 전 조회 1,242
10년 전 조회 1,211
10년 전 조회 1,455
10년 전 조회 1,268
10년 전 조회 1,231
10년 전 조회 1,241
10년 전 조회 1,188
10년 전 조회 1,112
10년 전 조회 1,111
10년 전 조회 1,206
10년 전 조회 1,210
10년 전 조회 1,129
10년 전 조회 1,025
10년 전 조회 1,111
10년 전 조회 1,084
10년 전 조회 1,108
10년 전 조회 1,162
10년 전 조회 1,154
10년 전 조회 1,098
10년 전 조회 1,113
10년 전 조회 1,162
10년 전 조회 1,119
10년 전 조회 1,196
10년 전 조회 1,134
10년 전 조회 1,066
10년 전 조회 1,049
10년 전 조회 1,065
10년 전 조회 1,048
10년 전 조회 1,076
10년 전 조회 1,105
10년 전 조회 1,055
10년 전 조회 1,128
10년 전 조회 1,058
10년 전 조회 1,168
10년 전 조회 1,249
10년 전 조회 1,210
10년 전 조회 1,159
10년 전 조회 1,078
10년 전 조회 1,190
10년 전 조회 1,103
10년 전 조회 1,140
10년 전 조회 1,080
10년 전 조회 1,061
10년 전 조회 1,064
10년 전 조회 1,087
10년 전 조회 1,187
10년 전 조회 1,126
10년 전 조회 1,214
10년 전 조회 1,099
10년 전 조회 1,126
10년 전 조회 1,114
10년 전 조회 1,181
10년 전 조회 1,268
10년 전 조회 1,347