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

· 10년 전 · 937

<?

// 퀵 정렬(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년 전 조회 980
9년 전 조회 979
9년 전 조회 1,116
9년 전 조회 957
9년 전 조회 1,078
9년 전 조회 886
9년 전 조회 969
9년 전 조회 815
9년 전 조회 1,005
9년 전 조회 875
9년 전 조회 883
9년 전 조회 950
9년 전 조회 933
9년 전 조회 915
9년 전 조회 890
9년 전 조회 1,257
9년 전 조회 1,315
9년 전 조회 1,305
10년 전 조회 1,218
10년 전 조회 1,038
10년 전 조회 1,160
10년 전 조회 1,318
10년 전 조회 982
10년 전 조회 1,378
10년 전 조회 1,263
10년 전 조회 1,656
10년 전 조회 1,272
10년 전 조회 1,452
10년 전 조회 1,081
10년 전 조회 1,252
10년 전 조회 949
10년 전 조회 994
10년 전 조회 1,093
10년 전 조회 1,073
10년 전 조회 1,214
10년 전 조회 1,051
10년 전 조회 1,051
10년 전 조회 1,016
10년 전 조회 942
10년 전 조회 1,046
10년 전 조회 879
10년 전 조회 925
10년 전 조회 842
10년 전 조회 967
10년 전 조회 936
10년 전 조회 1,404
10년 전 조회 911
10년 전 조회 842
10년 전 조회 1,092
10년 전 조회 938
10년 전 조회 887
10년 전 조회 903
10년 전 조회 856
10년 전 조회 802
10년 전 조회 765
10년 전 조회 845
10년 전 조회 872
10년 전 조회 837
10년 전 조회 769
10년 전 조회 838
10년 전 조회 822
10년 전 조회 832
10년 전 조회 894
10년 전 조회 896
10년 전 조회 819
10년 전 조회 849
10년 전 조회 907
10년 전 조회 926
10년 전 조회 939
10년 전 조회 872
10년 전 조회 808
10년 전 조회 791
10년 전 조회 819
10년 전 조회 788
10년 전 조회 806
10년 전 조회 853
10년 전 조회 781
10년 전 조회 824
10년 전 조회 807
10년 전 조회 884
10년 전 조회 994
10년 전 조회 947
10년 전 조회 908
10년 전 조회 807
10년 전 조회 931
10년 전 조회 830
10년 전 조회 868
10년 전 조회 812
10년 전 조회 812
10년 전 조회 783
10년 전 조회 812
10년 전 조회 918
10년 전 조회 856
10년 전 조회 964
10년 전 조회 827
10년 전 조회 871
10년 전 조회 846
10년 전 조회 902
10년 전 조회 1,070
10년 전 조회 1,064