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

· 10년 전 · 1227

<?

// 퀵 정렬(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,402
9년 전 조회 1,393
9년 전 조회 1,522
9년 전 조회 1,384
9년 전 조회 1,495
9년 전 조회 1,333
9년 전 조회 1,403
9년 전 조회 1,230
9년 전 조회 1,459
9년 전 조회 1,275
9년 전 조회 1,279
9년 전 조회 1,372
10년 전 조회 1,301
10년 전 조회 1,324
10년 전 조회 1,244
10년 전 조회 1,654
10년 전 조회 1,704
10년 전 조회 1,672
10년 전 조회 1,611
10년 전 조회 1,399
10년 전 조회 1,541
10년 전 조회 1,683
10년 전 조회 1,372
10년 전 조회 1,681
10년 전 조회 1,656
10년 전 조회 2,024
10년 전 조회 1,628
10년 전 조회 1,845
10년 전 조회 1,480
10년 전 조회 1,599
10년 전 조회 1,331
10년 전 조회 1,386
10년 전 조회 1,454
10년 전 조회 1,449
10년 전 조회 1,586
10년 전 조회 1,367
10년 전 조회 1,399
10년 전 조회 1,349
10년 전 조회 1,319
10년 전 조회 1,360
10년 전 조회 1,207
10년 전 조회 1,250
10년 전 조회 1,172
10년 전 조회 1,297
10년 전 조회 1,250
10년 전 조회 1,726
10년 전 조회 1,211
10년 전 조회 1,173
10년 전 조회 1,421
10년 전 조회 1,228
10년 전 조회 1,201
10년 전 조회 1,205
10년 전 조회 1,159
10년 전 조회 1,091
10년 전 조회 1,073
10년 전 조회 1,164
10년 전 조회 1,171
10년 전 조회 1,098
10년 전 조회 996
10년 전 조회 1,077
10년 전 조회 1,050
10년 전 조회 1,084
10년 전 조회 1,126
10년 전 조회 1,116
10년 전 조회 1,069
10년 전 조회 1,076
10년 전 조회 1,132
10년 전 조회 1,082
10년 전 조회 1,167
10년 전 조회 1,103
10년 전 조회 1,037
10년 전 조회 1,008
10년 전 조회 1,041
10년 전 조회 998
10년 전 조회 1,039
10년 전 조회 1,074
10년 전 조회 1,020
10년 전 조회 1,086
10년 전 조회 1,035
10년 전 조회 1,124
10년 전 조회 1,217
10년 전 조회 1,174
10년 전 조회 1,126
10년 전 조회 1,047
10년 전 조회 1,152
10년 전 조회 1,075
10년 전 조회 1,109
10년 전 조회 1,051
10년 전 조회 1,039
10년 전 조회 1,037
10년 전 조회 1,053
10년 전 조회 1,163
10년 전 조회 1,093
10년 전 조회 1,176
10년 전 조회 1,060
10년 전 조회 1,087
10년 전 조회 1,079
10년 전 조회 1,140
10년 전 조회 1,234
10년 전 조회 1,309