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

· 10년 전 · 1024

<?

// 퀵 정렬(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년 전 조회 1,131
9년 전 조회 1,119
9년 전 조회 1,247
9년 전 조회 1,097
9년 전 조회 1,206
9년 전 조회 1,053
9년 전 조회 1,105
9년 전 조회 954
9년 전 조회 1,150
9년 전 조회 1,011
9년 전 조회 1,015
9년 전 조회 1,086
9년 전 조회 1,054
9년 전 조회 1,057
9년 전 조회 1,001
9년 전 조회 1,386
10년 전 조회 1,458
10년 전 조회 1,416
10년 전 조회 1,346
10년 전 조회 1,150
10년 전 조회 1,294
10년 전 조회 1,439
10년 전 조회 1,100
10년 전 조회 1,480
10년 전 조회 1,409
10년 전 조회 1,766
10년 전 조회 1,383
10년 전 조회 1,588
10년 전 조회 1,215
10년 전 조회 1,377
10년 전 조회 1,080
10년 전 조회 1,127
10년 전 조회 1,211
10년 전 조회 1,200
10년 전 조회 1,328
10년 전 조회 1,160
10년 전 조회 1,178
10년 전 조회 1,138
10년 전 조회 1,073
10년 전 조회 1,153
10년 전 조회 997
10년 전 조회 1,042
10년 전 조회 954
10년 전 조회 1,083
10년 전 조회 1,041
10년 전 조회 1,501
10년 전 조회 999
10년 전 조회 949
10년 전 조회 1,192
10년 전 조회 1,025
10년 전 조회 993
10년 전 조회 1,003
10년 전 조회 973
10년 전 조회 902
10년 전 조회 868
10년 전 조회 948
10년 전 조회 980
10년 전 조회 914
10년 전 조회 835
10년 전 조회 904
10년 전 조회 869
10년 전 조회 906
10년 전 조회 953
10년 전 조회 956
10년 전 조회 889
10년 전 조회 905
10년 전 조회 964
10년 전 조회 967
10년 전 조회 1,009
10년 전 조회 936
10년 전 조회 877
10년 전 조회 864
10년 전 조회 884
10년 전 조회 849
10년 전 조회 873
10년 전 조회 910
10년 전 조회 860
10년 전 조회 903
10년 전 조회 874
10년 전 조회 959
10년 전 조회 1,071
10년 전 조회 1,022
10년 전 조회 968
10년 전 조회 883
10년 전 조회 987
10년 전 조회 905
10년 전 조회 931
10년 전 조회 892
10년 전 조회 875
10년 전 조회 868
10년 전 조회 894
10년 전 조회 989
10년 전 조회 928
10년 전 조회 1,015
10년 전 조회 890
10년 전 조회 924
10년 전 조회 913
10년 전 조회 964
10년 전 조회 1,112
10년 전 조회 1,125