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

· 10년 전 · 645

<?

// 퀵 정렬(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년 전 조회 688
9년 전 조회 698
9년 전 조회 821
9년 전 조회 659
9년 전 조회 795
9년 전 조회 592
9년 전 조회 669
9년 전 조회 522
9년 전 조회 731
9년 전 조회 614
9년 전 조회 640
9년 전 조회 689
9년 전 조회 638
9년 전 조회 644
9년 전 조회 619
9년 전 조회 997
9년 전 조회 1,029
9년 전 조회 1,006
9년 전 조회 958
9년 전 조회 744
9년 전 조회 906
9년 전 조회 1,028
9년 전 조회 727
9년 전 조회 1,012
9년 전 조회 972
10년 전 조회 1,388
10년 전 조회 998
10년 전 조회 1,187
10년 전 조회 828
10년 전 조회 976
10년 전 조회 702
10년 전 조회 715
10년 전 조회 825
10년 전 조회 799
10년 전 조회 971
10년 전 조회 693
10년 전 조회 760
10년 전 조회 734
10년 전 조회 645
10년 전 조회 749
10년 전 조회 597
10년 전 조회 650
10년 전 조회 585
10년 전 조회 671
10년 전 조회 655
10년 전 조회 1,110
10년 전 조회 614
10년 전 조회 553
10년 전 조회 815
10년 전 조회 646
10년 전 조회 612
10년 전 조회 603
10년 전 조회 571
10년 전 조회 509
10년 전 조회 489
10년 전 조회 562
10년 전 조회 572
10년 전 조회 528
10년 전 조회 474
10년 전 조회 560
10년 전 조회 538
10년 전 조회 547
10년 전 조회 602
10년 전 조회 609
10년 전 조회 503
10년 전 조회 546
10년 전 조회 603
10년 전 조회 540
10년 전 조회 626
10년 전 조회 566
10년 전 조회 515
10년 전 조회 486
10년 전 조회 516
10년 전 조회 485
10년 전 조회 509
10년 전 조회 542
10년 전 조회 473
10년 전 조회 523
10년 전 조회 484
10년 전 조회 587
10년 전 조회 688
10년 전 조회 636
10년 전 조회 605
10년 전 조회 519
10년 전 조회 618
10년 전 조회 531
10년 전 조회 561
10년 전 조회 518
10년 전 조회 500
10년 전 조회 484
10년 전 조회 525
10년 전 조회 597
10년 전 조회 546
10년 전 조회 624
10년 전 조회 530
10년 전 조회 557
10년 전 조회 536
10년 전 조회 591
10년 전 조회 675
10년 전 조회 766