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

· 10년 전 · 1253

<?

// 퀵 정렬(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,433
9년 전 조회 1,433
9년 전 조회 1,544
9년 전 조회 1,403
9년 전 조회 1,523
10년 전 조회 1,359
10년 전 조회 1,432
10년 전 조회 1,255
10년 전 조회 1,480
10년 전 조회 1,296
10년 전 조회 1,308
10년 전 조회 1,403
10년 전 조회 1,335
10년 전 조회 1,347
10년 전 조회 1,275
10년 전 조회 1,686
10년 전 조회 1,730
10년 전 조회 1,702
10년 전 조회 1,635
10년 전 조회 1,430
10년 전 조회 1,571
10년 전 조회 1,717
10년 전 조회 1,403
10년 전 조회 1,710
10년 전 조회 1,679
10년 전 조회 2,059
10년 전 조회 1,655
10년 전 조회 1,881
10년 전 조회 1,512
10년 전 조회 1,632
10년 전 조회 1,361
10년 전 조회 1,415
10년 전 조회 1,488
10년 전 조회 1,482
10년 전 조회 1,613
10년 전 조회 1,391
10년 전 조회 1,422
10년 전 조회 1,375
10년 전 조회 1,339
10년 전 조회 1,396
10년 전 조회 1,231
10년 전 조회 1,277
10년 전 조회 1,191
10년 전 조회 1,328
10년 전 조회 1,274
10년 전 조회 1,752
10년 전 조회 1,234
10년 전 조회 1,196
10년 전 조회 1,447
10년 전 조회 1,254
10년 전 조회 1,221
10년 전 조회 1,234
10년 전 조회 1,176
10년 전 조회 1,106
10년 전 조회 1,101
10년 전 조회 1,191
10년 전 조회 1,196
10년 전 조회 1,118
10년 전 조회 1,016
10년 전 조회 1,102
10년 전 조회 1,068
10년 전 조회 1,102
10년 전 조회 1,148
10년 전 조회 1,143
10년 전 조회 1,090
10년 전 조회 1,098
10년 전 조회 1,153
10년 전 조회 1,107
10년 전 조회 1,184
10년 전 조회 1,125
10년 전 조회 1,057
10년 전 조회 1,035
10년 전 조회 1,059
10년 전 조회 1,032
10년 전 조회 1,066
10년 전 조회 1,094
10년 전 조회 1,043
10년 전 조회 1,117
10년 전 조회 1,048
10년 전 조회 1,161
10년 전 조회 1,245
10년 전 조회 1,201
10년 전 조회 1,152
10년 전 조회 1,069
10년 전 조회 1,181
10년 전 조회 1,095
10년 전 조회 1,131
10년 전 조회 1,073
10년 전 조회 1,053
10년 전 조회 1,056
10년 전 조회 1,076
10년 전 조회 1,180
10년 전 조회 1,117
10년 전 조회 1,201
10년 전 조회 1,087
10년 전 조회 1,113
10년 전 조회 1,108
10년 전 조회 1,168
10년 전 조회 1,255
10년 전 조회 1,334