COMING SOON 🚀

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

· 10년 전 · 1311

<?

// 퀵 정렬(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,493
10년 전 조회 1,496
10년 전 조회 1,617
10년 전 조회 1,479
10년 전 조회 1,585
10년 전 조회 1,415
10년 전 조회 1,496
10년 전 조회 1,318
10년 전 조회 1,542
10년 전 조회 1,344
10년 전 조회 1,371
10년 전 조회 1,478
10년 전 조회 1,382
10년 전 조회 1,413
10년 전 조회 1,342
10년 전 조회 1,755
10년 전 조회 1,787
10년 전 조회 1,754
10년 전 조회 1,705
10년 전 조회 1,493
10년 전 조회 1,627
10년 전 조회 1,777
10년 전 조회 1,480
10년 전 조회 1,780
10년 전 조회 1,741
10년 전 조회 2,125
10년 전 조회 1,729
10년 전 조회 1,938
10년 전 조회 1,568
10년 전 조회 1,695
10년 전 조회 1,421
10년 전 조회 1,478
10년 전 조회 1,541
10년 전 조회 1,533
10년 전 조회 1,683
10년 전 조회 1,453
10년 전 조회 1,478
10년 전 조회 1,445
10년 전 조회 1,388
10년 전 조회 1,459
10년 전 조회 1,269
10년 전 조회 1,339
10년 전 조회 1,242
10년 전 조회 1,381
10년 전 조회 1,331
10년 전 조회 1,806
10년 전 조회 1,284
10년 전 조회 1,253
10년 전 조회 1,511
10년 전 조회 1,312
10년 전 조회 1,291
10년 전 조회 1,294
10년 전 조회 1,234
10년 전 조회 1,160
10년 전 조회 1,146
10년 전 조회 1,244
10년 전 조회 1,244
10년 전 조회 1,178
10년 전 조회 1,069
10년 전 조회 1,160
10년 전 조회 1,133
10년 전 조회 1,151
10년 전 조회 1,196
10년 전 조회 1,202
10년 전 조회 1,141
10년 전 조회 1,145
10년 전 조회 1,196
10년 전 조회 1,165
10년 전 조회 1,242
10년 전 조회 1,168
10년 전 조회 1,117
10년 전 조회 1,096
10년 전 조회 1,107
10년 전 조회 1,097
10년 전 조회 1,117
10년 전 조회 1,143
10년 전 조회 1,110
10년 전 조회 1,166
10년 전 조회 1,097
10년 전 조회 1,200
10년 전 조회 1,284
10년 전 조회 1,259
10년 전 조회 1,194
10년 전 조회 1,116
10년 전 조회 1,244
10년 전 조회 1,148
10년 전 조회 1,175
10년 전 조회 1,124
10년 전 조회 1,106
10년 전 조회 1,106
10년 전 조회 1,123
10년 전 조회 1,218
10년 전 조회 1,159
10년 전 조회 1,247
10년 전 조회 1,143
10년 전 조회 1,169
10년 전 조회 1,158
10년 전 조회 1,213
10년 전 조회 1,316
10년 전 조회 1,393