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

· 10년 전 · 1566

<?

// 퀵 정렬(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,696
10년 전 조회 1,727
10년 전 조회 1,846
10년 전 조회 1,690
10년 전 조회 1,825
10년 전 조회 1,601
10년 전 조회 1,695
10년 전 조회 1,494
10년 전 조회 1,735
10년 전 조회 1,513
10년 전 조회 1,588
10년 전 조회 1,685
10년 전 조회 1,577
10년 전 조회 1,621
10년 전 조회 1,557
10년 전 조회 1,962
10년 전 조회 1,975
10년 전 조회 1,963
10년 전 조회 1,941
10년 전 조회 1,712
10년 전 조회 1,828
10년 전 조회 2,003
10년 전 조회 1,699
10년 전 조회 1,986
10년 전 조회 1,959
10년 전 조회 2,337
10년 전 조회 1,945
10년 전 조회 2,163
10년 전 조회 1,771
10년 전 조회 1,933
10년 전 조회 1,624
10년 전 조회 1,717
10년 전 조회 1,748
10년 전 조회 1,750
10년 전 조회 1,914
10년 전 조회 1,686
10년 전 조회 1,721
10년 전 조회 1,724
10년 전 조회 1,631
10년 전 조회 1,686
10년 전 조회 1,490
10년 전 조회 1,570
10년 전 조회 1,484
10년 전 조회 1,636
10년 전 조회 1,590
10년 전 조회 2,052
10년 전 조회 1,526
10년 전 조회 1,495
10년 전 조회 1,756
10년 전 조회 1,567
10년 전 조회 1,529
10년 전 조회 1,537
10년 전 조회 1,495
10년 전 조회 1,420
10년 전 조회 1,385
10년 전 조회 1,517
10년 전 조회 1,485
10년 전 조회 1,435
10년 전 조회 1,320
10년 전 조회 1,399
10년 전 조회 1,432
10년 전 조회 1,418
10년 전 조회 1,471
10년 전 조회 1,453
10년 전 조회 1,409
10년 전 조회 1,413
10년 전 조회 1,459
10년 전 조회 1,433
10년 전 조회 1,522
10년 전 조회 1,423
10년 전 조회 1,376
10년 전 조회 1,346
10년 전 조회 1,374
10년 전 조회 1,392
10년 전 조회 1,392
10년 전 조회 1,410
10년 전 조회 1,361
10년 전 조회 1,426
10년 전 조회 1,356
10년 전 조회 1,455
10년 전 조회 1,544
10년 전 조회 1,519
10년 전 조회 1,444
10년 전 조회 1,374
10년 전 조회 1,510
10년 전 조회 1,406
10년 전 조회 1,448
10년 전 조회 1,395
10년 전 조회 1,371
10년 전 조회 1,367
10년 전 조회 1,394
10년 전 조회 1,485
10년 전 조회 1,406
10년 전 조회 1,497
10년 전 조회 1,401
10년 전 조회 1,456
10년 전 조회 1,453
10년 전 조회 1,509
10년 전 조회 1,568
10년 전 조회 1,642