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

· 10년 전 · 942

<?

// 퀵 정렬(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년 전 조회 989
9년 전 조회 988
9년 전 조회 1,132
9년 전 조회 969
9년 전 조회 1,087
9년 전 조회 895
9년 전 조회 983
9년 전 조회 828
9년 전 조회 1,019
9년 전 조회 885
9년 전 조회 895
9년 전 조회 962
9년 전 조회 944
9년 전 조회 932
9년 전 조회 896
9년 전 조회 1,265
9년 전 조회 1,324
10년 전 조회 1,312
10년 전 조회 1,228
10년 전 조회 1,049
10년 전 조회 1,167
10년 전 조회 1,329
10년 전 조회 991
10년 전 조회 1,385
10년 전 조회 1,273
10년 전 조회 1,662
10년 전 조회 1,282
10년 전 조회 1,462
10년 전 조회 1,092
10년 전 조회 1,257
10년 전 조회 958
10년 전 조회 1,005
10년 전 조회 1,100
10년 전 조회 1,079
10년 전 조회 1,223
10년 전 조회 1,059
10년 전 조회 1,057
10년 전 조회 1,019
10년 전 조회 947
10년 전 조회 1,054
10년 전 조회 889
10년 전 조회 935
10년 전 조회 853
10년 전 조회 977
10년 전 조회 943
10년 전 조회 1,411
10년 전 조회 919
10년 전 조회 850
10년 전 조회 1,101
10년 전 조회 943
10년 전 조회 895
10년 전 조회 911
10년 전 조회 864
10년 전 조회 811
10년 전 조회 767
10년 전 조회 852
10년 전 조회 879
10년 전 조회 840
10년 전 조회 774
10년 전 조회 843
10년 전 조회 826
10년 전 조회 841
10년 전 조회 899
10년 전 조회 900
10년 전 조회 825
10년 전 조회 852
10년 전 조회 910
10년 전 조회 927
10년 전 조회 946
10년 전 조회 878
10년 전 조회 814
10년 전 조회 795
10년 전 조회 826
10년 전 조회 790
10년 전 조회 812
10년 전 조회 858
10년 전 조회 784
10년 전 조회 830
10년 전 조회 814
10년 전 조회 891
10년 전 조회 998
10년 전 조회 953
10년 전 조회 912
10년 전 조회 810
10년 전 조회 936
10년 전 조회 837
10년 전 조회 876
10년 전 조회 821
10년 전 조회 821
10년 전 조회 790
10년 전 조회 818
10년 전 조회 920
10년 전 조회 860
10년 전 조회 969
10년 전 조회 833
10년 전 조회 877
10년 전 조회 849
10년 전 조회 907
10년 전 조회 1,073
10년 전 조회 1,070