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

· 10년 전 · 962

<?

// 퀵 정렬(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년 전 조회 1,028
9년 전 조회 1,035
9년 전 조회 1,160
9년 전 조회 1,007
9년 전 조회 1,120
9년 전 조회 944
9년 전 조회 1,016
9년 전 조회 863
9년 전 조회 1,048
9년 전 조회 909
9년 전 조회 918
9년 전 조회 981
9년 전 조회 966
9년 전 조회 956
9년 전 조회 918
9년 전 조회 1,292
9년 전 조회 1,352
10년 전 조회 1,329
10년 전 조회 1,247
10년 전 조회 1,068
10년 전 조회 1,193
10년 전 조회 1,349
10년 전 조회 1,013
10년 전 조회 1,409
10년 전 조회 1,294
10년 전 조회 1,681
10년 전 조회 1,296
10년 전 조회 1,490
10년 전 조회 1,116
10년 전 조회 1,281
10년 전 조회 980
10년 전 조회 1,032
10년 전 조회 1,116
10년 전 조회 1,111
10년 전 조회 1,249
10년 전 조회 1,086
10년 전 조회 1,090
10년 전 조회 1,049
10년 전 조회 977
10년 전 조회 1,073
10년 전 조회 910
10년 전 조회 958
10년 전 조회 875
10년 전 조회 990
10년 전 조회 964
10년 전 조회 1,426
10년 전 조회 938
10년 전 조회 865
10년 전 조회 1,123
10년 전 조회 963
10년 전 조회 916
10년 전 조회 926
10년 전 조회 894
10년 전 조회 840
10년 전 조회 786
10년 전 조회 868
10년 전 조회 905
10년 전 조회 855
10년 전 조회 788
10년 전 조회 856
10년 전 조회 834
10년 전 조회 851
10년 전 조회 909
10년 전 조회 908
10년 전 조회 839
10년 전 조회 866
10년 전 조회 921
10년 전 조회 936
10년 전 조회 960
10년 전 조회 895
10년 전 조회 830
10년 전 조회 813
10년 전 조회 844
10년 전 조회 795
10년 전 조회 834
10년 전 조회 866
10년 전 조회 792
10년 전 조회 844
10년 전 조회 829
10년 전 조회 912
10년 전 조회 1,016
10년 전 조회 967
10년 전 조회 924
10년 전 조회 823
10년 전 조회 949
10년 전 조회 851
10년 전 조회 887
10년 전 조회 838
10년 전 조회 832
10년 전 조회 805
10년 전 조회 834
10년 전 조회 931
10년 전 조회 878
10년 전 조회 976
10년 전 조회 844
10년 전 조회 883
10년 전 조회 866
10년 전 조회 917
10년 전 조회 1,078
10년 전 조회 1,083