COMING SOON 🚀

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

· 10년 전 · 1323

<?

// 퀵 정렬(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,499
10년 전 조회 1,504
10년 전 조회 1,625
10년 전 조회 1,483
10년 전 조회 1,591
10년 전 조회 1,422
10년 전 조회 1,501
10년 전 조회 1,323
10년 전 조회 1,545
10년 전 조회 1,350
10년 전 조회 1,376
10년 전 조회 1,488
10년 전 조회 1,392
10년 전 조회 1,420
10년 전 조회 1,350
10년 전 조회 1,759
10년 전 조회 1,796
10년 전 조회 1,757
10년 전 조회 1,717
10년 전 조회 1,497
10년 전 조회 1,632
10년 전 조회 1,785
10년 전 조회 1,487
10년 전 조회 1,791
10년 전 조회 1,749
10년 전 조회 2,134
10년 전 조회 1,740
10년 전 조회 1,947
10년 전 조회 1,575
10년 전 조회 1,704
10년 전 조회 1,430
10년 전 조회 1,485
10년 전 조회 1,550
10년 전 조회 1,541
10년 전 조회 1,689
10년 전 조회 1,465
10년 전 조회 1,487
10년 전 조회 1,453
10년 전 조회 1,399
10년 전 조회 1,468
10년 전 조회 1,280
10년 전 조회 1,348
10년 전 조회 1,250
10년 전 조회 1,392
10년 전 조회 1,340
10년 전 조회 1,815
10년 전 조회 1,290
10년 전 조회 1,261
10년 전 조회 1,516
10년 전 조회 1,324
10년 전 조회 1,298
10년 전 조회 1,304
10년 전 조회 1,245
10년 전 조회 1,173
10년 전 조회 1,158
10년 전 조회 1,250
10년 전 조회 1,252
10년 전 조회 1,184
10년 전 조회 1,083
10년 전 조회 1,166
10년 전 조회 1,140
10년 전 조회 1,156
10년 전 조회 1,210
10년 전 조회 1,215
10년 전 조회 1,155
10년 전 조회 1,160
10년 전 조회 1,209
10년 전 조회 1,169
10년 전 조회 1,249
10년 전 조회 1,175
10년 전 조회 1,123
10년 전 조회 1,103
10년 전 조회 1,116
10년 전 조회 1,103
10년 전 조회 1,123
10년 전 조회 1,154
10년 전 조회 1,117
10년 전 조회 1,174
10년 전 조회 1,107
10년 전 조회 1,206
10년 전 조회 1,292
10년 전 조회 1,265
10년 전 조회 1,205
10년 전 조회 1,128
10년 전 조회 1,247
10년 전 조회 1,157
10년 전 조회 1,181
10년 전 조회 1,133
10년 전 조회 1,113
10년 전 조회 1,110
10년 전 조회 1,130
10년 전 조회 1,225
10년 전 조회 1,165
10년 전 조회 1,253
10년 전 조회 1,146
10년 전 조회 1,177
10년 전 조회 1,164
10년 전 조회 1,224
10년 전 조회 1,320
10년 전 조회 1,398