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

· 10년 전 · 1485

<?

// 퀵 정렬(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,599
10년 전 조회 1,652
10년 전 조회 1,772
10년 전 조회 1,609
10년 전 조회 1,732
10년 전 조회 1,535
10년 전 조회 1,618
10년 전 조회 1,429
10년 전 조회 1,662
10년 전 조회 1,458
10년 전 조회 1,507
10년 전 조회 1,614
10년 전 조회 1,513
10년 전 조회 1,556
10년 전 조회 1,480
10년 전 조회 1,887
10년 전 조회 1,908
10년 전 조회 1,894
10년 전 조회 1,858
10년 전 조회 1,641
10년 전 조회 1,760
10년 전 조회 1,936
10년 전 조회 1,637
10년 전 조회 1,920
10년 전 조회 1,890
10년 전 조회 2,269
10년 전 조회 1,877
10년 전 조회 2,089
10년 전 조회 1,699
10년 전 조회 1,873
10년 전 조회 1,563
10년 전 조회 1,643
10년 전 조회 1,684
10년 전 조회 1,682
10년 전 조회 1,856
10년 전 조회 1,615
10년 전 조회 1,648
10년 전 조회 1,656
10년 전 조회 1,561
10년 전 조회 1,620
10년 전 조회 1,434
10년 전 조회 1,513
10년 전 조회 1,427
10년 전 조회 1,583
10년 전 조회 1,532
10년 전 조회 1,990
10년 전 조회 1,450
10년 전 조회 1,427
10년 전 조회 1,688
10년 전 조회 1,486
10년 전 조회 1,453
10년 전 조회 1,465
10년 전 조회 1,416
10년 전 조회 1,351
10년 전 조회 1,318
10년 전 조회 1,439
10년 전 조회 1,408
10년 전 조회 1,363
10년 전 조회 1,249
10년 전 조회 1,330
10년 전 조회 1,335
10년 전 조회 1,352
10년 전 조회 1,396
10년 전 조회 1,381
10년 전 조회 1,331
10년 전 조회 1,331
10년 전 조회 1,385
10년 전 조회 1,355
10년 전 조회 1,442
10년 전 조회 1,354
10년 전 조회 1,308
10년 전 조회 1,281
10년 전 조회 1,302
10년 전 조회 1,312
10년 전 조회 1,309
10년 전 조회 1,332
10년 전 조회 1,280
10년 전 조회 1,334
10년 전 조회 1,280
10년 전 조회 1,380
10년 전 조회 1,468
10년 전 조회 1,434
10년 전 조회 1,367
10년 전 조회 1,285
10년 전 조회 1,414
10년 전 조회 1,309
10년 전 조회 1,364
10년 전 조회 1,305
10년 전 조회 1,275
10년 전 조회 1,261
10년 전 조회 1,292
10년 전 조회 1,372
10년 전 조회 1,312
10년 전 조회 1,398
10년 전 조회 1,314
10년 전 조회 1,356
10년 전 조회 1,339
10년 전 조회 1,398
10년 전 조회 1,481
10년 전 조회 1,546