COMING SOON 🚀

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

· 10년 전 · 1285

<?

// 퀵 정렬(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,466
10년 전 조회 1,472
10년 전 조회 1,586
10년 전 조회 1,450
10년 전 조회 1,559
10년 전 조회 1,397
10년 전 조회 1,471
10년 전 조회 1,294
10년 전 조회 1,519
10년 전 조회 1,328
10년 전 조회 1,350
10년 전 조회 1,453
10년 전 조회 1,368
10년 전 조회 1,391
10년 전 조회 1,310
10년 전 조회 1,733
10년 전 조회 1,763
10년 전 조회 1,732
10년 전 조회 1,672
10년 전 조회 1,464
10년 전 조회 1,605
10년 전 조회 1,753
10년 전 조회 1,444
10년 전 조회 1,757
10년 전 조회 1,716
10년 전 조회 2,095
10년 전 조회 1,696
10년 전 조회 1,908
10년 전 조회 1,546
10년 전 조회 1,671
10년 전 조회 1,401
10년 전 조회 1,453
10년 전 조회 1,517
10년 전 조회 1,510
10년 전 조회 1,659
10년 전 조회 1,427
10년 전 조회 1,454
10년 전 조회 1,419
10년 전 조회 1,369
10년 전 조회 1,434
10년 전 조회 1,249
10년 전 조회 1,315
10년 전 조회 1,220
10년 전 조회 1,364
10년 전 조회 1,314
10년 전 조회 1,785
10년 전 조회 1,259
10년 전 조회 1,225
10년 전 조회 1,481
10년 전 조회 1,286
10년 전 조회 1,254
10년 전 조회 1,264
10년 전 조회 1,214
10년 전 조회 1,126
10년 전 조회 1,127
10년 전 조회 1,226
10년 전 조회 1,224
10년 전 조회 1,153
10년 전 조회 1,042
10년 전 조회 1,134
10년 전 조회 1,112
10년 전 조회 1,131
10년 전 조회 1,176
10년 전 조회 1,175
10년 전 조회 1,118
10년 전 조회 1,127
10년 전 조회 1,181
10년 전 조회 1,142
10년 전 조회 1,222
10년 전 조회 1,151
10년 전 조회 1,093
10년 전 조회 1,072
10년 전 조회 1,079
10년 전 조회 1,064
10년 전 조회 1,094
10년 전 조회 1,124
10년 전 조회 1,079
10년 전 조회 1,144
10년 전 조회 1,077
10년 전 조회 1,190
10년 전 조회 1,270
10년 전 조회 1,235
10년 전 조회 1,175
10년 전 조회 1,102
10년 전 조회 1,216
10년 전 조회 1,125
10년 전 조회 1,158
10년 전 조회 1,099
10년 전 조회 1,080
10년 전 조회 1,081
10년 전 조회 1,105
10년 전 조회 1,200
10년 전 조회 1,148
10년 전 조회 1,232
10년 전 조회 1,119
10년 전 조회 1,149
10년 전 조회 1,141
10년 전 조회 1,192
10년 전 조회 1,296
10년 전 조회 1,372