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

· 10년 전 · 1064

<?

// 퀵 정렬(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,174
9년 전 조회 1,165
9년 전 조회 1,310
9년 전 조회 1,133
9년 전 조회 1,248
9년 전 조회 1,102
9년 전 조회 1,153
9년 전 조회 996
9년 전 조회 1,201
9년 전 조회 1,057
9년 전 조회 1,076
9년 전 조회 1,140
9년 전 조회 1,103
9년 전 조회 1,103
9년 전 조회 1,046
10년 전 조회 1,425
10년 전 조회 1,506
10년 전 조회 1,464
10년 전 조회 1,386
10년 전 조회 1,200
10년 전 조회 1,334
10년 전 조회 1,474
10년 전 조회 1,155
10년 전 조회 1,509
10년 전 조회 1,448
10년 전 조회 1,807
10년 전 조회 1,429
10년 전 조회 1,637
10년 전 조회 1,265
10년 전 조회 1,422
10년 전 조회 1,126
10년 전 조회 1,173
10년 전 조회 1,259
10년 전 조회 1,244
10년 전 조회 1,366
10년 전 조회 1,194
10년 전 조회 1,205
10년 전 조회 1,169
10년 전 조회 1,114
10년 전 조회 1,191
10년 전 조회 1,042
10년 전 조회 1,080
10년 전 조회 989
10년 전 조회 1,112
10년 전 조회 1,076
10년 전 조회 1,543
10년 전 조회 1,029
10년 전 조회 991
10년 전 조회 1,237
10년 전 조회 1,065
10년 전 조회 1,025
10년 전 조회 1,040
10년 전 조회 1,009
10년 전 조회 947
10년 전 조회 914
10년 전 조회 977
10년 전 조회 1,010
10년 전 조회 940
10년 전 조회 866
10년 전 조회 936
10년 전 조회 898
10년 전 조회 937
10년 전 조회 971
10년 전 조회 981
10년 전 조회 914
10년 전 조회 931
10년 전 조회 987
10년 전 조회 983
10년 전 조회 1,029
10년 전 조회 963
10년 전 조회 906
10년 전 조회 885
10년 전 조회 902
10년 전 조회 869
10년 전 조회 904
10년 전 조회 938
10년 전 조회 887
10년 전 조회 935
10년 전 조회 901
10년 전 조회 986
10년 전 조회 1,092
10년 전 조회 1,043
10년 전 조회 998
10년 전 조회 916
10년 전 조회 1,016
10년 전 조회 928
10년 전 조회 961
10년 전 조회 922
10년 전 조회 906
10년 전 조회 891
10년 전 조회 921
10년 전 조회 1,015
10년 전 조회 954
10년 전 조회 1,042
10년 전 조회 925
10년 전 조회 955
10년 전 조회 944
10년 전 조회 996
10년 전 조회 1,133
10년 전 조회 1,159