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

· 10년 전 · 1428

<?

// 퀵 정렬(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,569
10년 전 조회 1,592
10년 전 조회 1,719
10년 전 조회 1,570
10년 전 조회 1,676
10년 전 조회 1,489
10년 전 조회 1,575
10년 전 조회 1,394
10년 전 조회 1,618
10년 전 조회 1,412
10년 전 조회 1,456
10년 전 조회 1,565
10년 전 조회 1,471
10년 전 조회 1,506
10년 전 조회 1,429
10년 전 조회 1,843
10년 전 조회 1,871
10년 전 조회 1,850
10년 전 조회 1,808
10년 전 조회 1,591
10년 전 조회 1,714
10년 전 조회 1,882
10년 전 조회 1,595
10년 전 조회 1,870
10년 전 조회 1,850
10년 전 조회 2,227
10년 전 조회 1,829
10년 전 조회 2,037
10년 전 조회 1,671
10년 전 조회 1,818
10년 전 조회 1,517
10년 전 조회 1,585
10년 전 조회 1,637
10년 전 조회 1,627
10년 전 조회 1,790
10년 전 조회 1,559
10년 전 조회 1,587
10년 전 조회 1,597
10년 전 조회 1,506
10년 전 조회 1,567
10년 전 조회 1,379
10년 전 조회 1,456
10년 전 조회 1,354
10년 전 조회 1,517
10년 전 조회 1,463
10년 전 조회 1,930
10년 전 조회 1,398
10년 전 조회 1,366
10년 전 조회 1,626
10년 전 조회 1,429
10년 전 조회 1,403
10년 전 조회 1,400
10년 전 조회 1,354
10년 전 조회 1,285
10년 전 조회 1,256
10년 전 조회 1,376
10년 전 조회 1,347
10년 전 조회 1,300
10년 전 조회 1,191
10년 전 조회 1,270
10년 전 조회 1,249
10년 전 조회 1,281
10년 전 조회 1,320
10년 전 조회 1,318
10년 전 조회 1,275
10년 전 조회 1,270
10년 전 조회 1,304
10년 전 조회 1,287
10년 전 조회 1,362
10년 전 조회 1,272
10년 전 조회 1,228
10년 전 조회 1,212
10년 전 조회 1,224
10년 전 조회 1,225
10년 전 조회 1,237
10년 전 조회 1,252
10년 전 조회 1,211
10년 전 조회 1,267
10년 전 조회 1,204
10년 전 조회 1,303
10년 전 조회 1,388
10년 전 조회 1,362
10년 전 조회 1,300
10년 전 조회 1,221
10년 전 조회 1,347
10년 전 조회 1,233
10년 전 조회 1,273
10년 전 조회 1,238
10년 전 조회 1,197
10년 전 조회 1,198
10년 전 조회 1,221
10년 전 조회 1,302
10년 전 조회 1,243
10년 전 조회 1,333
10년 전 조회 1,238
10년 전 조회 1,278
10년 전 조회 1,261
10년 전 조회 1,313
10년 전 조회 1,404
10년 전 조회 1,478