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

· 10년 전 · 667

<?

// 퀵 정렬(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년 전 조회 714
9년 전 조회 722
9년 전 조회 858
9년 전 조회 690
9년 전 조회 823
9년 전 조회 619
9년 전 조회 700
9년 전 조회 549
9년 전 조회 760
9년 전 조회 640
9년 전 조회 667
9년 전 조회 723
9년 전 조회 669
9년 전 조회 679
9년 전 조회 650
9년 전 조회 1,025
9년 전 조회 1,058
9년 전 조회 1,047
9년 전 조회 985
9년 전 조회 775
9년 전 조회 931
9년 전 조회 1,060
9년 전 조회 764
9년 전 조회 1,049
9년 전 조회 1,006
10년 전 조회 1,415
10년 전 조회 1,028
10년 전 조회 1,220
10년 전 조회 847
10년 전 조회 1,009
10년 전 조회 724
10년 전 조회 747
10년 전 조회 870
10년 전 조회 835
10년 전 조회 998
10년 전 조회 734
10년 전 조회 794
10년 전 조회 761
10년 전 조회 679
10년 전 조회 783
10년 전 조회 628
10년 전 조회 683
10년 전 조회 613
10년 전 조회 706
10년 전 조회 681
10년 전 조회 1,130
10년 전 조회 650
10년 전 조회 580
10년 전 조회 847
10년 전 조회 668
10년 전 조회 641
10년 전 조회 641
10년 전 조회 594
10년 전 조회 535
10년 전 조회 520
10년 전 조회 594
10년 전 조회 609
10년 전 조회 558
10년 전 조회 508
10년 전 조회 595
10년 전 조회 563
10년 전 조회 572
10년 전 조회 629
10년 전 조회 640
10년 전 조회 531
10년 전 조회 572
10년 전 조회 630
10년 전 조회 572
10년 전 조회 660
10년 전 조회 598
10년 전 조회 543
10년 전 조회 520
10년 전 조회 548
10년 전 조회 506
10년 전 조회 541
10년 전 조회 573
10년 전 조회 511
10년 전 조회 557
10년 전 조회 517
10년 전 조회 612
10년 전 조회 712
10년 전 조회 667
10년 전 조회 638
10년 전 조회 540
10년 전 조회 644
10년 전 조회 559
10년 전 조회 593
10년 전 조회 548
10년 전 조회 530
10년 전 조회 519
10년 전 조회 548
10년 전 조회 626
10년 전 조회 578
10년 전 조회 655
10년 전 조회 559
10년 전 조회 580
10년 전 조회 570
10년 전 조회 616
10년 전 조회 703
10년 전 조회 797