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

· 10년 전 · 1205

<?

// 퀵 정렬(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,366
9년 전 조회 1,354
9년 전 조회 1,493
9년 전 조회 1,339
9년 전 조회 1,461
9년 전 조회 1,291
9년 전 조회 1,369
9년 전 조회 1,202
9년 전 조회 1,424
9년 전 조회 1,255
9년 전 조회 1,253
9년 전 조회 1,329
9년 전 조회 1,277
9년 전 조회 1,298
9년 전 조회 1,212
10년 전 조회 1,626
10년 전 조회 1,678
10년 전 조회 1,633
10년 전 조회 1,581
10년 전 조회 1,373
10년 전 조회 1,502
10년 전 조회 1,656
10년 전 조회 1,345
10년 전 조회 1,655
10년 전 조회 1,626
10년 전 조회 1,992
10년 전 조회 1,604
10년 전 조회 1,820
10년 전 조회 1,448
10년 전 조회 1,568
10년 전 조회 1,310
10년 전 조회 1,346
10년 전 조회 1,426
10년 전 조회 1,416
10년 전 조회 1,557
10년 전 조회 1,338
10년 전 조회 1,375
10년 전 조회 1,324
10년 전 조회 1,290
10년 전 조회 1,339
10년 전 조회 1,179
10년 전 조회 1,229
10년 전 조회 1,146
10년 전 조회 1,263
10년 전 조회 1,235
10년 전 조회 1,707
10년 전 조회 1,182
10년 전 조회 1,146
10년 전 조회 1,392
10년 전 조회 1,206
10년 전 조회 1,175
10년 전 조회 1,180
10년 전 조회 1,138
10년 전 조회 1,070
10년 전 조회 1,053
10년 전 조회 1,126
10년 전 조회 1,148
10년 전 조회 1,074
10년 전 조회 983
10년 전 조회 1,061
10년 전 조회 1,025
10년 전 조회 1,067
10년 전 조회 1,098
10년 전 조회 1,099
10년 전 조회 1,039
10년 전 조회 1,052
10년 전 조회 1,111
10년 전 조회 1,061
10년 전 조회 1,139
10년 전 조회 1,088
10년 전 조회 1,021
10년 전 조회 989
10년 전 조회 1,022
10년 전 조회 975
10년 전 조회 1,021
10년 전 조회 1,052
10년 전 조회 1,002
10년 전 조회 1,062
10년 전 조회 1,023
10년 전 조회 1,099
10년 전 조회 1,196
10년 전 조회 1,151
10년 전 조회 1,104
10년 전 조회 1,027
10년 전 조회 1,131
10년 전 조회 1,062
10년 전 조회 1,087
10년 전 조회 1,033
10년 전 조회 1,022
10년 전 조회 1,016
10년 전 조회 1,042
10년 전 조회 1,148
10년 전 조회 1,078
10년 전 조회 1,163
10년 전 조회 1,032
10년 전 조회 1,064
10년 전 조회 1,051
10년 전 조회 1,122
10년 전 조회 1,210
10년 전 조회 1,285