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

· 10년 전 · 1620

<?

// 퀵 정렬(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,761
10년 전 조회 1,789
10년 전 조회 1,900
10년 전 조회 1,755
10년 전 조회 1,884
10년 전 조회 1,652
10년 전 조회 1,763
10년 전 조회 1,549
10년 전 조회 1,789
10년 전 조회 1,565
10년 전 조회 1,635
10년 전 조회 1,738
10년 전 조회 1,628
10년 전 조회 1,658
10년 전 조회 1,616
10년 전 조회 2,022
10년 전 조회 2,030
10년 전 조회 2,022
10년 전 조회 1,988
10년 전 조회 1,765
10년 전 조회 1,885
10년 전 조회 2,046
10년 전 조회 1,746
10년 전 조회 2,039
10년 전 조회 2,002
10년 전 조회 2,386
10년 전 조회 1,997
10년 전 조회 2,210
10년 전 조회 1,817
10년 전 조회 1,977
10년 전 조회 1,668
10년 전 조회 1,756
10년 전 조회 1,789
10년 전 조회 1,801
10년 전 조회 1,958
10년 전 조회 1,728
10년 전 조회 1,757
10년 전 조회 1,775
10년 전 조회 1,676
10년 전 조회 1,732
10년 전 조회 1,543
10년 전 조회 1,612
10년 전 조회 1,533
10년 전 조회 1,689
10년 전 조회 1,635
10년 전 조회 2,106
10년 전 조회 1,578
10년 전 조회 1,539
10년 전 조회 1,805
10년 전 조회 1,621
10년 전 조회 1,573
10년 전 조회 1,578
10년 전 조회 1,549
10년 전 조회 1,461
10년 전 조회 1,438
10년 전 조회 1,549
10년 전 조회 1,521
10년 전 조회 1,478
10년 전 조회 1,372
10년 전 조회 1,442
10년 전 조회 1,478
10년 전 조회 1,458
10년 전 조회 1,530
10년 전 조회 1,496
10년 전 조회 1,461
10년 전 조회 1,454
10년 전 조회 1,500
10년 전 조회 1,472
10년 전 조회 1,561
10년 전 조회 1,463
10년 전 조회 1,417
10년 전 조회 1,390
10년 전 조회 1,417
10년 전 조회 1,437
10년 전 조회 1,430
10년 전 조회 1,456
10년 전 조회 1,393
10년 전 조회 1,470
10년 전 조회 1,411
10년 전 조회 1,496
10년 전 조회 1,585
10년 전 조회 1,566
10년 전 조회 1,488
10년 전 조회 1,412
10년 전 조회 1,557
10년 전 조회 1,452
10년 전 조회 1,488
10년 전 조회 1,436
10년 전 조회 1,421
10년 전 조회 1,409
10년 전 조회 1,440
10년 전 조회 1,537
10년 전 조회 1,457
10년 전 조회 1,547
10년 전 조회 1,448
10년 전 조회 1,511
10년 전 조회 1,500
10년 전 조회 1,554
10년 전 조회 1,622
10년 전 조회 1,694