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

· 10년 전 · 1116

<?

// 퀵 정렬(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,266
9년 전 조회 1,244
9년 전 조회 1,375
9년 전 조회 1,217
9년 전 조회 1,350
9년 전 조회 1,171
9년 전 조회 1,245
9년 전 조회 1,082
9년 전 조회 1,302
9년 전 조회 1,162
9년 전 조회 1,168
9년 전 조회 1,219
9년 전 조회 1,170
9년 전 조회 1,196
9년 전 조회 1,126
10년 전 조회 1,513
10년 전 조회 1,576
10년 전 조회 1,533
10년 전 조회 1,477
10년 전 조회 1,268
10년 전 조회 1,406
10년 전 조회 1,559
10년 전 조회 1,239
10년 전 조회 1,587
10년 전 조회 1,544
10년 전 조회 1,898
10년 전 조회 1,504
10년 전 조회 1,716
10년 전 조회 1,342
10년 전 조회 1,488
10년 전 조회 1,210
10년 전 조회 1,258
10년 전 조회 1,333
10년 전 조회 1,333
10년 전 조회 1,445
10년 전 조회 1,256
10년 전 조회 1,280
10년 전 조회 1,233
10년 전 조회 1,203
10년 전 조회 1,260
10년 전 조회 1,108
10년 전 조회 1,145
10년 전 조회 1,058
10년 전 조회 1,179
10년 전 조회 1,154
10년 전 조회 1,623
10년 전 조회 1,101
10년 전 조회 1,060
10년 전 조회 1,313
10년 전 조회 1,117
10년 전 조회 1,087
10년 전 조회 1,096
10년 전 조회 1,072
10년 전 조회 1,007
10년 전 조회 979
10년 전 조회 1,051
10년 전 조회 1,066
10년 전 조회 1,001
10년 전 조회 920
10년 전 조회 993
10년 전 조회 951
10년 전 조회 993
10년 전 조회 1,030
10년 전 조회 1,029
10년 전 조회 972
10년 전 조회 983
10년 전 조회 1,043
10년 전 조회 1,015
10년 전 조회 1,074
10년 전 조회 1,026
10년 전 조회 958
10년 전 조회 929
10년 전 조회 951
10년 전 조회 922
10년 전 조회 957
10년 전 조회 987
10년 전 조회 939
10년 전 조회 991
10년 전 조회 956
10년 전 조회 1,038
10년 전 조회 1,151
10년 전 조회 1,101
10년 전 조회 1,046
10년 전 조회 972
10년 전 조회 1,063
10년 전 조회 988
10년 전 조회 1,019
10년 전 조회 967
10년 전 조회 964
10년 전 조회 950
10년 전 조회 981
10년 전 조회 1,070
10년 전 조회 1,011
10년 전 조회 1,094
10년 전 조회 968
10년 전 조회 1,004
10년 전 조회 991
10년 전 조회 1,052
10년 전 조회 1,172
10년 전 조회 1,205