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

· 10년 전 · 669

<?

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

?>

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

프로그램

+
제목 글쓴이 날짜 조회
9년 전 조회 717
9년 전 조회 722
9년 전 조회 860
9년 전 조회 692
9년 전 조회 823
9년 전 조회 622
9년 전 조회 701
9년 전 조회 549
9년 전 조회 762
9년 전 조회 641
9년 전 조회 667
9년 전 조회 725
9년 전 조회 671
9년 전 조회 681
9년 전 조회 653
9년 전 조회 1,027
9년 전 조회 1,060
9년 전 조회 1,048
9년 전 조회 986
9년 전 조회 778
9년 전 조회 931
9년 전 조회 1,064
9년 전 조회 767
9년 전 조회 1,051
9년 전 조회 1,012
10년 전 조회 1,421
10년 전 조회 1,029
10년 전 조회 1,223
10년 전 조회 848
10년 전 조회 1,010
10년 전 조회 727
10년 전 조회 748
10년 전 조회 873
10년 전 조회 837
10년 전 조회 999
10년 전 조회 735
10년 전 조회 797
10년 전 조회 765
10년 전 조회 679
10년 전 조회 785
10년 전 조회 630
10년 전 조회 687
10년 전 조회 615
10년 전 조회 707
10년 전 조회 681
10년 전 조회 1,133
10년 전 조회 654
10년 전 조회 582
10년 전 조회 849
10년 전 조회 670
10년 전 조회 642
10년 전 조회 644
10년 전 조회 596
10년 전 조회 537
10년 전 조회 521
10년 전 조회 595
10년 전 조회 613
10년 전 조회 558
10년 전 조회 510
10년 전 조회 596
10년 전 조회 565
10년 전 조회 575
10년 전 조회 632
10년 전 조회 641
10년 전 조회 533
10년 전 조회 573
10년 전 조회 630
10년 전 조회 572
10년 전 조회 661
10년 전 조회 598
10년 전 조회 544
10년 전 조회 521
10년 전 조회 552
10년 전 조회 506
10년 전 조회 542
10년 전 조회 576
10년 전 조회 511
10년 전 조회 560
10년 전 조회 518
10년 전 조회 614
10년 전 조회 714
10년 전 조회 669
10년 전 조회 639
10년 전 조회 541
10년 전 조회 646
10년 전 조회 560
10년 전 조회 595
10년 전 조회 549
10년 전 조회 533
10년 전 조회 520
10년 전 조회 549
10년 전 조회 627
10년 전 조회 580
10년 전 조회 656
10년 전 조회 561
10년 전 조회 583
10년 전 조회 571
10년 전 조회 619
10년 전 조회 708
10년 전 조회 798