COMING SOON 🚀

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

· 10년 전 · 1340

<?

// 퀵 정렬(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);

?>

|
댓글을 작성하시려면 로그인이 필요합니다.

프로그램

+
제목 글쓴이 날짜 조회
10년 전 조회 1,504
10년 전 조회 1,510
10년 전 조회 1,639
10년 전 조회 1,493
10년 전 조회 1,600
10년 전 조회 1,426
10년 전 조회 1,508
10년 전 조회 1,329
10년 전 조회 1,550
10년 전 조회 1,362
10년 전 조회 1,389
10년 전 조회 1,498
10년 전 조회 1,396
10년 전 조회 1,429
10년 전 조회 1,357
10년 전 조회 1,769
10년 전 조회 1,805
10년 전 조회 1,765
10년 전 조회 1,727
10년 전 조회 1,506
10년 전 조회 1,641
10년 전 조회 1,793
10년 전 조회 1,502
10년 전 조회 1,801
10년 전 조회 1,758
10년 전 조회 2,145
10년 전 조회 1,753
10년 전 조회 1,957
10년 전 조회 1,583
10년 전 조회 1,715
10년 전 조회 1,437
10년 전 조회 1,497
10년 전 조회 1,560
10년 전 조회 1,549
10년 전 조회 1,702
10년 전 조회 1,470
10년 전 조회 1,502
10년 전 조회 1,468
10년 전 조회 1,411
10년 전 조회 1,474
10년 전 조회 1,289
10년 전 조회 1,358
10년 전 조회 1,266
10년 전 조회 1,406
10년 전 조회 1,352
10년 전 조회 1,829
10년 전 조회 1,303
10년 전 조회 1,274
10년 전 조회 1,528
10년 전 조회 1,341
10년 전 조회 1,308
10년 전 조회 1,318
10년 전 조회 1,256
10년 전 조회 1,187
10년 전 조회 1,169
10년 전 조회 1,261
10년 전 조회 1,260
10년 전 조회 1,194
10년 전 조회 1,092
10년 전 조회 1,176
10년 전 조회 1,148
10년 전 조회 1,169
10년 전 조회 1,224
10년 전 조회 1,227
10년 전 조회 1,165
10년 전 조회 1,171
10년 전 조회 1,215
10년 전 조회 1,184
10년 전 조회 1,258
10년 전 조회 1,182
10년 전 조회 1,133
10년 전 조회 1,113
10년 전 조회 1,133
10년 전 조회 1,112
10년 전 조회 1,137
10년 전 조회 1,159
10년 전 조회 1,125
10년 전 조회 1,178
10년 전 조회 1,122
10년 전 조회 1,212
10년 전 조회 1,307
10년 전 조회 1,273
10년 전 조회 1,215
10년 전 조회 1,141
10년 전 조회 1,250
10년 전 조회 1,168
10년 전 조회 1,186
10년 전 조회 1,141
10년 전 조회 1,123
10년 전 조회 1,121
10년 전 조회 1,141
10년 전 조회 1,232
10년 전 조회 1,180
10년 전 조회 1,259
10년 전 조회 1,151
10년 전 조회 1,187
10년 전 조회 1,171
10년 전 조회 1,232
10년 전 조회 1,326
10년 전 조회 1,409