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

· 10년 전 · 1240

<?

// 퀵 정렬(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,423
9년 전 조회 1,416
9년 전 조회 1,536
9년 전 조회 1,394
9년 전 조회 1,510
9년 전 조회 1,344
9년 전 조회 1,419
9년 전 조회 1,246
10년 전 조회 1,471
10년 전 조회 1,286
10년 전 조회 1,296
10년 전 조회 1,390
10년 전 조회 1,321
10년 전 조회 1,336
10년 전 조회 1,260
10년 전 조회 1,673
10년 전 조회 1,720
10년 전 조회 1,688
10년 전 조회 1,624
10년 전 조회 1,418
10년 전 조회 1,559
10년 전 조회 1,699
10년 전 조회 1,386
10년 전 조회 1,694
10년 전 조회 1,670
10년 전 조회 2,042
10년 전 조회 1,643
10년 전 조회 1,868
10년 전 조회 1,492
10년 전 조회 1,617
10년 전 조회 1,347
10년 전 조회 1,403
10년 전 조회 1,473
10년 전 조회 1,469
10년 전 조회 1,596
10년 전 조회 1,381
10년 전 조회 1,411
10년 전 조회 1,362
10년 전 조회 1,328
10년 전 조회 1,379
10년 전 조회 1,218
10년 전 조회 1,262
10년 전 조회 1,181
10년 전 조회 1,322
10년 전 조회 1,260
10년 전 조회 1,740
10년 전 조회 1,227
10년 전 조회 1,185
10년 전 조회 1,433
10년 전 조회 1,241
10년 전 조회 1,213
10년 전 조회 1,221
10년 전 조회 1,170
10년 전 조회 1,100
10년 전 조회 1,087
10년 전 조회 1,182
10년 전 조회 1,185
10년 전 조회 1,109
10년 전 조회 1,006
10년 전 조회 1,087
10년 전 조회 1,057
10년 전 조회 1,096
10년 전 조회 1,136
10년 전 조회 1,131
10년 전 조회 1,082
10년 전 조회 1,088
10년 전 조회 1,144
10년 전 조회 1,097
10년 전 조회 1,177
10년 전 조회 1,115
10년 전 조회 1,047
10년 전 조회 1,027
10년 전 조회 1,051
10년 전 조회 1,016
10년 전 조회 1,056
10년 전 조회 1,083
10년 전 조회 1,036
10년 전 조회 1,107
10년 전 조회 1,043
10년 전 조회 1,146
10년 전 조회 1,230
10년 전 조회 1,190
10년 전 조회 1,136
10년 전 조회 1,060
10년 전 조회 1,164
10년 전 조회 1,082
10년 전 조회 1,116
10년 전 조회 1,060
10년 전 조회 1,045
10년 전 조회 1,047
10년 전 조회 1,068
10년 전 조회 1,172
10년 전 조회 1,108
10년 전 조회 1,194
10년 전 조회 1,070
10년 전 조회 1,098
10년 전 조회 1,090
10년 전 조회 1,151
10년 전 조회 1,244
10년 전 조회 1,321