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

· 10년 전 · 1479

<?

// 퀵 정렬(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,595
10년 전 조회 1,647
10년 전 조회 1,768
10년 전 조회 1,608
10년 전 조회 1,730
10년 전 조회 1,533
10년 전 조회 1,616
10년 전 조회 1,427
10년 전 조회 1,656
10년 전 조회 1,456
10년 전 조회 1,504
10년 전 조회 1,613
10년 전 조회 1,512
10년 전 조회 1,550
10년 전 조회 1,478
10년 전 조회 1,884
10년 전 조회 1,904
10년 전 조회 1,893
10년 전 조회 1,853
10년 전 조회 1,641
10년 전 조회 1,757
10년 전 조회 1,933
10년 전 조회 1,637
10년 전 조회 1,917
10년 전 조회 1,888
10년 전 조회 2,267
10년 전 조회 1,874
10년 전 조회 2,080
10년 전 조회 1,698
10년 전 조회 1,867
10년 전 조회 1,558
10년 전 조회 1,640
10년 전 조회 1,681
10년 전 조회 1,680
10년 전 조회 1,850
10년 전 조회 1,612
10년 전 조회 1,642
10년 전 조회 1,652
10년 전 조회 1,558
10년 전 조회 1,616
10년 전 조회 1,433
10년 전 조회 1,511
10년 전 조회 1,421
10년 전 조회 1,578
10년 전 조회 1,521
10년 전 조회 1,986
10년 전 조회 1,446
10년 전 조회 1,425
10년 전 조회 1,687
10년 전 조회 1,480
10년 전 조회 1,450
10년 전 조회 1,459
10년 전 조회 1,412
10년 전 조회 1,344
10년 전 조회 1,314
10년 전 조회 1,434
10년 전 조회 1,402
10년 전 조회 1,359
10년 전 조회 1,244
10년 전 조회 1,325
10년 전 조회 1,332
10년 전 조회 1,344
10년 전 조회 1,391
10년 전 조회 1,377
10년 전 조회 1,326
10년 전 조회 1,328
10년 전 조회 1,373
10년 전 조회 1,349
10년 전 조회 1,435
10년 전 조회 1,345
10년 전 조회 1,303
10년 전 조회 1,276
10년 전 조회 1,297
10년 전 조회 1,309
10년 전 조회 1,305
10년 전 조회 1,329
10년 전 조회 1,272
10년 전 조회 1,332
10년 전 조회 1,274
10년 전 조회 1,375
10년 전 조회 1,461
10년 전 조회 1,430
10년 전 조회 1,363
10년 전 조회 1,279
10년 전 조회 1,407
10년 전 조회 1,304
10년 전 조회 1,355
10년 전 조회 1,300
10년 전 조회 1,266
10년 전 조회 1,254
10년 전 조회 1,287
10년 전 조회 1,368
10년 전 조회 1,309
10년 전 조회 1,393
10년 전 조회 1,306
10년 전 조회 1,349
10년 전 조회 1,331
10년 전 조회 1,393
10년 전 조회 1,476
10년 전 조회 1,538