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

· 10년 전 · 1078

<?

// 퀵 정렬(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,192
9년 전 조회 1,185
9년 전 조회 1,323
9년 전 조회 1,149
9년 전 조회 1,268
9년 전 조회 1,124
9년 전 조회 1,176
9년 전 조회 1,018
9년 전 조회 1,225
9년 전 조회 1,082
9년 전 조회 1,101
9년 전 조회 1,161
9년 전 조회 1,124
9년 전 조회 1,127
9년 전 조회 1,064
10년 전 조회 1,444
10년 전 조회 1,526
10년 전 조회 1,483
10년 전 조회 1,409
10년 전 조회 1,212
10년 전 조회 1,350
10년 전 조회 1,497
10년 전 조회 1,177
10년 전 조회 1,525
10년 전 조회 1,472
10년 전 조회 1,831
10년 전 조회 1,454
10년 전 조회 1,660
10년 전 조회 1,280
10년 전 조회 1,437
10년 전 조회 1,157
10년 전 조회 1,191
10년 전 조회 1,277
10년 전 조회 1,277
10년 전 조회 1,385
10년 전 조회 1,209
10년 전 조회 1,217
10년 전 조회 1,184
10년 전 조회 1,135
10년 전 조회 1,217
10년 전 조회 1,060
10년 전 조회 1,098
10년 전 조회 1,009
10년 전 조회 1,123
10년 전 조회 1,098
10년 전 조회 1,566
10년 전 조회 1,049
10년 전 조회 1,011
10년 전 조회 1,258
10년 전 조회 1,079
10년 전 조회 1,034
10년 전 조회 1,052
10년 전 조회 1,029
10년 전 조회 961
10년 전 조회 935
10년 전 조회 990
10년 전 조회 1,016
10년 전 조회 956
10년 전 조회 879
10년 전 조회 945
10년 전 조회 908
10년 전 조회 945
10년 전 조회 986
10년 전 조회 990
10년 전 조회 935
10년 전 조회 939
10년 전 조회 1,002
10년 전 조회 990
10년 전 조회 1,044
10년 전 조회 979
10년 전 조회 913
10년 전 조회 897
10년 전 조회 916
10년 전 조회 885
10년 전 조회 916
10년 전 조회 951
10년 전 조회 904
10년 전 조회 950
10년 전 조회 908
10년 전 조회 995
10년 전 조회 1,104
10년 전 조회 1,055
10년 전 조회 1,008
10년 전 조회 934
10년 전 조회 1,031
10년 전 조회 939
10년 전 조회 978
10년 전 조회 929
10년 전 조회 920
10년 전 조회 912
10년 전 조회 942
10년 전 조회 1,021
10년 전 조회 968
10년 전 조회 1,053
10년 전 조회 937
10년 전 조회 971
10년 전 조회 959
10년 전 조회 1,009
10년 전 조회 1,144
10년 전 조회 1,170