COMING SOON 🚀

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

· 10년 전 · 1289

<?

// 퀵 정렬(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,474
10년 전 조회 1,478
10년 전 조회 1,588
10년 전 조회 1,455
10년 전 조회 1,566
10년 전 조회 1,399
10년 전 조회 1,474
10년 전 조회 1,296
10년 전 조회 1,521
10년 전 조회 1,328
10년 전 조회 1,353
10년 전 조회 1,460
10년 전 조회 1,370
10년 전 조회 1,396
10년 전 조회 1,319
10년 전 조회 1,737
10년 전 조회 1,767
10년 전 조회 1,735
10년 전 조회 1,680
10년 전 조회 1,469
10년 전 조회 1,607
10년 전 조회 1,756
10년 전 조회 1,450
10년 전 조회 1,765
10년 전 조회 1,720
10년 전 조회 2,098
10년 전 조회 1,703
10년 전 조회 1,910
10년 전 조회 1,552
10년 전 조회 1,680
10년 전 조회 1,403
10년 전 조회 1,458
10년 전 조회 1,521
10년 전 조회 1,514
10년 전 조회 1,664
10년 전 조회 1,431
10년 전 조회 1,458
10년 전 조회 1,421
10년 전 조회 1,373
10년 전 조회 1,440
10년 전 조회 1,250
10년 전 조회 1,324
10년 전 조회 1,222
10년 전 조회 1,366
10년 전 조회 1,316
10년 전 조회 1,791
10년 전 조회 1,265
10년 전 조회 1,229
10년 전 조회 1,484
10년 전 조회 1,290
10년 전 조회 1,259
10년 전 조회 1,273
10년 전 조회 1,217
10년 전 조회 1,134
10년 전 조회 1,129
10년 전 조회 1,227
10년 전 조회 1,229
10년 전 조회 1,159
10년 전 조회 1,048
10년 전 조회 1,139
10년 전 조회 1,113
10년 전 조회 1,134
10년 전 조회 1,179
10년 전 조회 1,182
10년 전 조회 1,124
10년 전 조회 1,128
10년 전 조회 1,186
10년 전 조회 1,144
10년 전 조회 1,226
10년 전 조회 1,151
10년 전 조회 1,099
10년 전 조회 1,075
10년 전 조회 1,084
10년 전 조회 1,068
10년 전 조회 1,100
10년 전 조회 1,128
10년 전 조회 1,086
10년 전 조회 1,148
10년 전 조회 1,081
10년 전 조회 1,190
10년 전 조회 1,272
10년 전 조회 1,242
10년 전 조회 1,178
10년 전 조회 1,103
10년 전 조회 1,223
10년 전 조회 1,129
10년 전 조회 1,161
10년 전 조회 1,104
10년 전 조회 1,084
10년 전 조회 1,086
10년 전 조회 1,109
10년 전 조회 1,202
10년 전 조회 1,151
10년 전 조회 1,237
10년 전 조회 1,124
10년 전 조회 1,154
10년 전 조회 1,144
10년 전 조회 1,194
10년 전 조회 1,299
10년 전 조회 1,378