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

· 10년 전 · 1381

<?

// 퀵 정렬(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);

?>

|
댓글을 작성하시려면 로그인이 필요합니다.

프로그램

+
제목 글쓴이 날짜 조회
10년 전 조회 1,533
10년 전 조회 1,547
10년 전 조회 1,686
10년 전 조회 1,532
10년 전 조회 1,632
10년 전 조회 1,463
10년 전 조회 1,544
10년 전 조회 1,366
10년 전 조회 1,586
10년 전 조회 1,393
10년 전 조회 1,427
10년 전 조회 1,537
10년 전 조회 1,436
10년 전 조회 1,471
10년 전 조회 1,402
10년 전 조회 1,814
10년 전 조회 1,840
10년 전 조회 1,810
10년 전 조회 1,773
10년 전 조회 1,548
10년 전 조회 1,680
10년 전 조회 1,851
10년 전 조회 1,561
10년 전 조회 1,843
10년 전 조회 1,819
10년 전 조회 2,193
10년 전 조회 1,801
10년 전 조회 1,998
10년 전 조회 1,636
10년 전 조회 1,779
10년 전 조회 1,483
10년 전 조회 1,547
10년 전 조회 1,604
10년 전 조회 1,590
10년 전 조회 1,744
10년 전 조회 1,515
10년 전 조회 1,546
10년 전 조회 1,528
10년 전 조회 1,451
10년 전 조회 1,523
10년 전 조회 1,336
10년 전 조회 1,405
10년 전 조회 1,314
10년 전 조회 1,469
10년 전 조회 1,405
10년 전 조회 1,886
10년 전 조회 1,351
10년 전 조회 1,313
10년 전 조회 1,574
10년 전 조회 1,382
10년 전 조회 1,362
10년 전 조회 1,356
10년 전 조회 1,300
10년 전 조회 1,231
10년 전 조회 1,205
10년 전 조회 1,310
10년 전 조회 1,304
10년 전 조회 1,242
10년 전 조회 1,132
10년 전 조회 1,216
10년 전 조회 1,202
10년 전 조회 1,212
10년 전 조회 1,268
10년 전 조회 1,271
10년 전 조회 1,212
10년 전 조회 1,211
10년 전 조회 1,254
10년 전 조회 1,230
10년 전 조회 1,314
10년 전 조회 1,223
10년 전 조회 1,177
10년 전 조회 1,160
10년 전 조회 1,173
10년 전 조회 1,157
10년 전 조회 1,181
10년 전 조회 1,194
10년 전 조회 1,162
10년 전 조회 1,228
10년 전 조회 1,161
10년 전 조회 1,250
10년 전 조회 1,334
10년 전 조회 1,313
10년 전 조회 1,258
10년 전 조회 1,174
10년 전 조회 1,294
10년 전 조회 1,199
10년 전 조회 1,218
10년 전 조회 1,181
10년 전 조회 1,146
10년 전 조회 1,151
10년 전 조회 1,167
10년 전 조회 1,260
10년 전 조회 1,201
10년 전 조회 1,279
10년 전 조회 1,184
10년 전 조회 1,214
10년 전 조회 1,209
10년 전 조회 1,261
10년 전 조회 1,356
10년 전 조회 1,432