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

· 10년 전 · 1423

<?

// 퀵 정렬(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,566
10년 전 조회 1,586
10년 전 조회 1,714
10년 전 조회 1,567
10년 전 조회 1,670
10년 전 조회 1,487
10년 전 조회 1,571
10년 전 조회 1,386
10년 전 조회 1,611
10년 전 조회 1,410
10년 전 조회 1,454
10년 전 조회 1,564
10년 전 조회 1,467
10년 전 조회 1,502
10년 전 조회 1,428
10년 전 조회 1,842
10년 전 조회 1,868
10년 전 조회 1,847
10년 전 조회 1,807
10년 전 조회 1,582
10년 전 조회 1,710
10년 전 조회 1,880
10년 전 조회 1,591
10년 전 조회 1,866
10년 전 조회 1,849
10년 전 조회 2,223
10년 전 조회 1,826
10년 전 조회 2,033
10년 전 조회 1,667
10년 전 조회 1,814
10년 전 조회 1,513
10년 전 조회 1,581
10년 전 조회 1,633
10년 전 조회 1,618
10년 전 조회 1,786
10년 전 조회 1,557
10년 전 조회 1,583
10년 전 조회 1,589
10년 전 조회 1,499
10년 전 조회 1,561
10년 전 조회 1,371
10년 전 조회 1,451
10년 전 조회 1,349
10년 전 조회 1,510
10년 전 조회 1,457
10년 전 조회 1,926
10년 전 조회 1,390
10년 전 조회 1,359
10년 전 조회 1,619
10년 전 조회 1,424
10년 전 조회 1,398
10년 전 조회 1,394
10년 전 조회 1,345
10년 전 조회 1,275
10년 전 조회 1,251
10년 전 조회 1,366
10년 전 조회 1,336
10년 전 조회 1,293
10년 전 조회 1,184
10년 전 조회 1,264
10년 전 조회 1,239
10년 전 조회 1,265
10년 전 조회 1,317
10년 전 조회 1,315
10년 전 조회 1,266
10년 전 조회 1,259
10년 전 조회 1,296
10년 전 조회 1,281
10년 전 조회 1,356
10년 전 조회 1,267
10년 전 조회 1,218
10년 전 조회 1,208
10년 전 조회 1,217
10년 전 조회 1,216
10년 전 조회 1,229
10년 전 조회 1,239
10년 전 조회 1,200
10년 전 조회 1,262
10년 전 조회 1,201
10년 전 조회 1,296
10년 전 조회 1,380
10년 전 조회 1,356
10년 전 조회 1,295
10년 전 조회 1,213
10년 전 조회 1,342
10년 전 조회 1,230
10년 전 조회 1,266
10년 전 조회 1,227
10년 전 조회 1,190
10년 전 조회 1,188
10년 전 조회 1,212
10년 전 조회 1,298
10년 전 조회 1,236
10년 전 조회 1,325
10년 전 조회 1,229
10년 전 조회 1,266
10년 전 조회 1,255
10년 전 조회 1,300
10년 전 조회 1,401
10년 전 조회 1,472