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

· 10년 전 · 1143

<?

// 퀵 정렬(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,296
9년 전 조회 1,290
9년 전 조회 1,423
9년 전 조회 1,259
9년 전 조회 1,382
9년 전 조회 1,209
9년 전 조회 1,291
9년 전 조회 1,127
9년 전 조회 1,342
9년 전 조회 1,205
9년 전 조회 1,193
9년 전 조회 1,250
9년 전 조회 1,207
9년 전 조회 1,239
9년 전 조회 1,159
10년 전 조회 1,556
10년 전 조회 1,615
10년 전 조회 1,564
10년 전 조회 1,512
10년 전 조회 1,295
10년 전 조회 1,447
10년 전 조회 1,598
10년 전 조회 1,284
10년 전 조회 1,607
10년 전 조회 1,571
10년 전 조회 1,935
10년 전 조회 1,543
10년 전 조회 1,756
10년 전 조회 1,375
10년 전 조회 1,522
10년 전 조회 1,239
10년 전 조회 1,291
10년 전 조회 1,363
10년 전 조회 1,360
10년 전 조회 1,483
10년 전 조회 1,285
10년 전 조회 1,313
10년 전 조회 1,268
10년 전 조회 1,236
10년 전 조회 1,286
10년 전 조회 1,134
10년 전 조회 1,181
10년 전 조회 1,091
10년 전 조회 1,202
10년 전 조회 1,182
10년 전 조회 1,657
10년 전 조회 1,130
10년 전 조회 1,087
10년 전 조회 1,343
10년 전 조회 1,144
10년 전 조회 1,122
10년 전 조회 1,122
10년 전 조회 1,095
10년 전 조회 1,024
10년 전 조회 1,004
10년 전 조회 1,076
10년 전 조회 1,103
10년 전 조회 1,022
10년 전 조회 939
10년 전 조회 1,020
10년 전 조회 974
10년 전 조회 1,018
10년 전 조회 1,053
10년 전 조회 1,052
10년 전 조회 998
10년 전 조회 1,008
10년 전 조회 1,066
10년 전 조회 1,032
10년 전 조회 1,097
10년 전 조회 1,042
10년 전 조회 979
10년 전 조회 949
10년 전 조회 974
10년 전 조회 939
10년 전 조회 980
10년 전 조회 1,011
10년 전 조회 960
10년 전 조회 1,023
10년 전 조회 981
10년 전 조회 1,066
10년 전 조회 1,164
10년 전 조회 1,125
10년 전 조회 1,072
10년 전 조회 1,000
10년 전 조회 1,090
10년 전 조회 1,017
10년 전 조회 1,040
10년 전 조회 992
10년 전 조회 984
10년 전 조회 974
10년 전 조회 1,000
10년 전 조회 1,105
10년 전 조회 1,037
10년 전 조회 1,117
10년 전 조회 993
10년 전 조회 1,022
10년 전 조회 1,008
10년 전 조회 1,073
10년 전 조회 1,182
10년 전 조회 1,237