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

· 10년 전 · 639

<?

// 퀵 정렬(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년 전 조회 676
9년 전 조회 694
9년 전 조회 812
9년 전 조회 654
9년 전 조회 789
9년 전 조회 583
9년 전 조회 661
9년 전 조회 520
9년 전 조회 722
9년 전 조회 608
9년 전 조회 632
9년 전 조회 680
9년 전 조회 632
9년 전 조회 637
9년 전 조회 613
9년 전 조회 986
9년 전 조회 1,024
9년 전 조회 1,001
9년 전 조회 955
9년 전 조회 740
9년 전 조회 896
9년 전 조회 1,022
9년 전 조회 720
9년 전 조회 1,004
9년 전 조회 964
10년 전 조회 1,382
10년 전 조회 992
10년 전 조회 1,178
10년 전 조회 824
10년 전 조회 967
10년 전 조회 698
10년 전 조회 710
10년 전 조회 819
10년 전 조회 788
10년 전 조회 968
10년 전 조회 681
10년 전 조회 752
10년 전 조회 731
10년 전 조회 638
10년 전 조회 740
10년 전 조회 593
10년 전 조회 644
10년 전 조회 579
10년 전 조회 668
10년 전 조회 650
10년 전 조회 1,104
10년 전 조회 609
10년 전 조회 543
10년 전 조회 807
10년 전 조회 640
10년 전 조회 608
10년 전 조회 594
10년 전 조회 563
10년 전 조회 502
10년 전 조회 481
10년 전 조회 551
10년 전 조회 565
10년 전 조회 522
10년 전 조회 466
10년 전 조회 554
10년 전 조회 537
10년 전 조회 534
10년 전 조회 599
10년 전 조회 604
10년 전 조회 496
10년 전 조회 536
10년 전 조회 595
10년 전 조회 530
10년 전 조회 619
10년 전 조회 560
10년 전 조회 507
10년 전 조회 479
10년 전 조회 510
10년 전 조회 485
10년 전 조회 502
10년 전 조회 529
10년 전 조회 463
10년 전 조회 516
10년 전 조회 477
10년 전 조회 581
10년 전 조회 683
10년 전 조회 629
10년 전 조회 596
10년 전 조회 511
10년 전 조회 612
10년 전 조회 524
10년 전 조회 554
10년 전 조회 510
10년 전 조회 490
10년 전 조회 479
10년 전 조회 518
10년 전 조회 585
10년 전 조회 533
10년 전 조회 619
10년 전 조회 524
10년 전 조회 550
10년 전 조회 527
10년 전 조회 586
10년 전 조회 664
10년 전 조회 762