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

· 10년 전 · 1482

<?

// 퀵 정렬(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,595
10년 전 조회 1,650
10년 전 조회 1,771
10년 전 조회 1,609
10년 전 조회 1,730
10년 전 조회 1,534
10년 전 조회 1,617
10년 전 조회 1,428
10년 전 조회 1,658
10년 전 조회 1,456
10년 전 조회 1,506
10년 전 조회 1,614
10년 전 조회 1,512
10년 전 조회 1,551
10년 전 조회 1,478
10년 전 조회 1,884
10년 전 조회 1,906
10년 전 조회 1,893
10년 전 조회 1,856
10년 전 조회 1,641
10년 전 조회 1,760
10년 전 조회 1,934
10년 전 조회 1,637
10년 전 조회 1,918
10년 전 조회 1,890
10년 전 조회 2,269
10년 전 조회 1,875
10년 전 조회 2,085
10년 전 조회 1,698
10년 전 조회 1,868
10년 전 조회 1,560
10년 전 조회 1,642
10년 전 조회 1,682
10년 전 조회 1,680
10년 전 조회 1,852
10년 전 조회 1,613
10년 전 조회 1,647
10년 전 조회 1,655
10년 전 조회 1,559
10년 전 조회 1,616
10년 전 조회 1,433
10년 전 조회 1,513
10년 전 조회 1,423
10년 전 조회 1,581
10년 전 조회 1,525
10년 전 조회 1,988
10년 전 조회 1,450
10년 전 조회 1,426
10년 전 조회 1,688
10년 전 조회 1,483
10년 전 조회 1,451
10년 전 조회 1,463
10년 전 조회 1,415
10년 전 조회 1,348
10년 전 조회 1,316
10년 전 조회 1,436
10년 전 조회 1,404
10년 전 조회 1,360
10년 전 조회 1,244
10년 전 조회 1,326
10년 전 조회 1,335
10년 전 조회 1,347
10년 전 조회 1,392
10년 전 조회 1,379
10년 전 조회 1,327
10년 전 조회 1,330
10년 전 조회 1,377
10년 전 조회 1,352
10년 전 조회 1,437
10년 전 조회 1,350
10년 전 조회 1,306
10년 전 조회 1,279
10년 전 조회 1,298
10년 전 조회 1,310
10년 전 조회 1,307
10년 전 조회 1,330
10년 전 조회 1,276
10년 전 조회 1,332
10년 전 조회 1,275
10년 전 조회 1,378
10년 전 조회 1,461
10년 전 조회 1,432
10년 전 조회 1,363
10년 전 조회 1,282
10년 전 조회 1,409
10년 전 조회 1,307
10년 전 조회 1,358
10년 전 조회 1,302
10년 전 조회 1,270
10년 전 조회 1,256
10년 전 조회 1,290
10년 전 조회 1,370
10년 전 조회 1,312
10년 전 조회 1,397
10년 전 조회 1,310
10년 전 조회 1,351
10년 전 조회 1,336
10년 전 조회 1,397
10년 전 조회 1,477
10년 전 조회 1,541