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

· 10년 전 · 1464

<?

// 퀵 정렬(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,591
10년 전 조회 1,631
10년 전 조회 1,754
10년 전 조회 1,595
10년 전 조회 1,718
10년 전 조회 1,519
10년 전 조회 1,603
10년 전 조회 1,420
10년 전 조회 1,646
10년 전 조회 1,447
10년 전 조회 1,494
10년 전 조회 1,600
10년 전 조회 1,498
10년 전 조회 1,535
10년 전 조회 1,461
10년 전 조회 1,877
10년 전 조회 1,890
10년 전 조회 1,880
10년 전 조회 1,841
10년 전 조회 1,627
10년 전 조회 1,748
10년 전 조회 1,916
10년 전 조회 1,626
10년 전 조회 1,902
10년 전 조회 1,879
10년 전 조회 2,256
10년 전 조회 1,857
10년 전 조회 2,069
10년 전 조회 1,695
10년 전 조회 1,848
10년 전 조회 1,544
10년 전 조회 1,624
10년 전 조회 1,668
10년 전 조회 1,666
10년 전 조회 1,833
10년 전 조회 1,595
10년 전 조회 1,626
10년 전 조회 1,631
10년 전 조회 1,543
10년 전 조회 1,600
10년 전 조회 1,413
10년 전 조회 1,496
10년 전 조회 1,407
10년 전 조회 1,560
10년 전 조회 1,496
10년 전 조회 1,967
10년 전 조회 1,430
10년 전 조회 1,406
10년 전 조회 1,664
10년 전 조회 1,465
10년 전 조회 1,438
10년 전 조회 1,441
10년 전 조회 1,390
10년 전 조회 1,323
10년 전 조회 1,296
10년 전 조회 1,413
10년 전 조회 1,384
10년 전 조회 1,339
10년 전 조회 1,224
10년 전 조회 1,307
10년 전 조회 1,306
10년 전 조회 1,325
10년 전 조회 1,371
10년 전 조회 1,364
10년 전 조회 1,312
10년 전 조회 1,310
10년 전 조회 1,359
10년 전 조회 1,333
10년 전 조회 1,420
10년 전 조회 1,323
10년 전 조회 1,276
10년 전 조회 1,258
10년 전 조회 1,277
10년 전 조회 1,286
10년 전 조회 1,287
10년 전 조회 1,308
10년 전 조회 1,255
10년 전 조회 1,319
10년 전 조회 1,246
10년 전 조회 1,352
10년 전 조회 1,439
10년 전 조회 1,414
10년 전 조회 1,344
10년 전 조회 1,260
10년 전 조회 1,389
10년 전 조회 1,288
10년 전 조회 1,333
10년 전 조회 1,276
10년 전 조회 1,248
10년 전 조회 1,236
10년 전 조회 1,272
10년 전 조회 1,343
10년 전 조회 1,293
10년 전 조회 1,380
10년 전 조회 1,289
10년 전 조회 1,335
10년 전 조회 1,307
10년 전 조회 1,370
10년 전 조회 1,452
10년 전 조회 1,518