COMING SOON 🚀

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

· 10년 전 · 1296

<?

// 퀵 정렬(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,480
10년 전 조회 1,487
10년 전 조회 1,599
10년 전 조회 1,465
10년 전 조회 1,574
10년 전 조회 1,406
10년 전 조회 1,478
10년 전 조회 1,303
10년 전 조회 1,533
10년 전 조회 1,335
10년 전 조회 1,360
10년 전 조회 1,466
10년 전 조회 1,372
10년 전 조회 1,402
10년 전 조회 1,326
10년 전 조회 1,743
10년 전 조회 1,776
10년 전 조회 1,740
10년 전 조회 1,686
10년 전 조회 1,478
10년 전 조회 1,617
10년 전 조회 1,761
10년 전 조회 1,458
10년 전 조회 1,771
10년 전 조회 1,732
10년 전 조회 2,107
10년 전 조회 1,714
10년 전 조회 1,921
10년 전 조회 1,555
10년 전 조회 1,685
10년 전 조회 1,406
10년 전 조회 1,464
10년 전 조회 1,529
10년 전 조회 1,519
10년 전 조회 1,667
10년 전 조회 1,439
10년 전 조회 1,465
10년 전 조회 1,426
10년 전 조회 1,380
10년 전 조회 1,447
10년 전 조회 1,252
10년 전 조회 1,328
10년 전 조회 1,224
10년 전 조회 1,371
10년 전 조회 1,322
10년 전 조회 1,795
10년 전 조회 1,269
10년 전 조회 1,239
10년 전 조회 1,490
10년 전 조회 1,297
10년 전 조회 1,268
10년 전 조회 1,282
10년 전 조회 1,223
10년 전 조회 1,144
10년 전 조회 1,136
10년 전 조회 1,232
10년 전 조회 1,231
10년 전 조회 1,165
10년 전 조회 1,059
10년 전 조회 1,144
10년 전 조회 1,118
10년 전 조회 1,136
10년 전 조회 1,184
10년 전 조회 1,192
10년 전 조회 1,131
10년 전 조회 1,133
10년 전 조회 1,192
10년 전 조회 1,153
10년 전 조회 1,232
10년 전 조회 1,159
10년 전 조회 1,105
10년 전 조회 1,082
10년 전 조회 1,093
10년 전 조회 1,078
10년 전 조회 1,108
10년 전 조회 1,136
10년 전 조회 1,097
10년 전 조회 1,152
10년 전 조회 1,087
10년 전 조회 1,194
10년 전 조회 1,275
10년 전 조회 1,248
10년 전 조회 1,184
10년 전 조회 1,107
10년 전 조회 1,229
10년 전 조회 1,136
10년 전 조회 1,169
10년 전 조회 1,110
10년 전 조회 1,094
10년 전 조회 1,092
10년 전 조회 1,114
10년 전 조회 1,209
10년 전 조회 1,155
10년 전 조회 1,243
10년 전 조회 1,132
10년 전 조회 1,158
10년 전 조회 1,152
10년 전 조회 1,198
10년 전 조회 1,304
10년 전 조회 1,382