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

· 10년 전 · 1575

<?

// 퀵 정렬(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,711
10년 전 조회 1,741
10년 전 조회 1,859
10년 전 조회 1,702
10년 전 조회 1,838
10년 전 조회 1,612
10년 전 조회 1,717
10년 전 조회 1,513
10년 전 조회 1,746
10년 전 조회 1,528
10년 전 조회 1,596
10년 전 조회 1,697
10년 전 조회 1,587
10년 전 조회 1,630
10년 전 조회 1,573
10년 전 조회 1,979
10년 전 조회 1,987
10년 전 조회 1,976
10년 전 조회 1,956
10년 전 조회 1,728
10년 전 조회 1,849
10년 전 조회 2,012
10년 전 조회 1,710
10년 전 조회 1,999
10년 전 조회 1,971
10년 전 조회 2,350
10년 전 조회 1,953
10년 전 조회 2,182
10년 전 조회 1,783
10년 전 조회 1,942
10년 전 조회 1,638
10년 전 조회 1,724
10년 전 조회 1,757
10년 전 조회 1,765
10년 전 조회 1,921
10년 전 조회 1,698
10년 전 조회 1,731
10년 전 조회 1,734
10년 전 조회 1,642
10년 전 조회 1,697
10년 전 조회 1,505
10년 전 조회 1,580
10년 전 조회 1,493
10년 전 조회 1,653
10년 전 조회 1,599
10년 전 조회 2,068
10년 전 조회 1,548
10년 전 조회 1,506
10년 전 조회 1,767
10년 전 조회 1,576
10년 전 조회 1,539
10년 전 조회 1,542
10년 전 조회 1,508
10년 전 조회 1,429
10년 전 조회 1,403
10년 전 조회 1,530
10년 전 조회 1,493
10년 전 조회 1,446
10년 전 조회 1,332
10년 전 조회 1,412
10년 전 조회 1,448
10년 전 조회 1,431
10년 전 조회 1,488
10년 전 조회 1,468
10년 전 조회 1,419
10년 전 조회 1,425
10년 전 조회 1,469
10년 전 조회 1,445
10년 전 조회 1,533
10년 전 조회 1,430
10년 전 조회 1,384
10년 전 조회 1,357
10년 전 조회 1,383
10년 전 조회 1,403
10년 전 조회 1,401
10년 전 조회 1,424
10년 전 조회 1,368
10년 전 조회 1,439
10년 전 조회 1,372
10년 전 조회 1,468
10년 전 조회 1,555
10년 전 조회 1,533
10년 전 조회 1,454
10년 전 조회 1,385
10년 전 조회 1,525
10년 전 조회 1,420
10년 전 조회 1,460
10년 전 조회 1,403
10년 전 조회 1,382
10년 전 조회 1,371
10년 전 조회 1,405
10년 전 조회 1,498
10년 전 조회 1,413
10년 전 조회 1,508
10년 전 조회 1,414
10년 전 조회 1,472
10년 전 조회 1,459
10년 전 조회 1,520
10년 전 조회 1,580
10년 전 조회 1,658