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

· 10년 전 · 1389

<?

// 퀵 정렬(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,538
10년 전 조회 1,561
10년 전 조회 1,695
10년 전 조회 1,538
10년 전 조회 1,642
10년 전 조회 1,468
10년 전 조회 1,549
10년 전 조회 1,369
10년 전 조회 1,589
10년 전 조회 1,396
10년 전 조회 1,431
10년 전 조회 1,546
10년 전 조회 1,437
10년 전 조회 1,473
10년 전 조회 1,409
10년 전 조회 1,822
10년 전 조회 1,843
10년 전 조회 1,817
10년 전 조회 1,782
10년 전 조회 1,553
10년 전 조회 1,684
10년 전 조회 1,857
10년 전 조회 1,566
10년 전 조회 1,846
10년 전 조회 1,823
10년 전 조회 2,197
10년 전 조회 1,805
10년 전 조회 2,000
10년 전 조회 1,643
10년 전 조회 1,785
10년 전 조회 1,488
10년 전 조회 1,553
10년 전 조회 1,610
10년 전 조회 1,595
10년 전 조회 1,753
10년 전 조회 1,519
10년 전 조회 1,552
10년 전 조회 1,537
10년 전 조회 1,461
10년 전 조회 1,531
10년 전 조회 1,341
10년 전 조회 1,414
10년 전 조회 1,319
10년 전 조회 1,477
10년 전 조회 1,407
10년 전 조회 1,890
10년 전 조회 1,354
10년 전 조회 1,322
10년 전 조회 1,582
10년 전 조회 1,390
10년 전 조회 1,367
10년 전 조회 1,359
10년 전 조회 1,308
10년 전 조회 1,233
10년 전 조회 1,209
10년 전 조회 1,316
10년 전 조회 1,306
10년 전 조회 1,248
10년 전 조회 1,138
10년 전 조회 1,224
10년 전 조회 1,210
10년 전 조회 1,216
10년 전 조회 1,274
10년 전 조회 1,276
10년 전 조회 1,219
10년 전 조회 1,220
10년 전 조회 1,266
10년 전 조회 1,239
10년 전 조회 1,318
10년 전 조회 1,232
10년 전 조회 1,184
10년 전 조회 1,169
10년 전 조회 1,180
10년 전 조회 1,162
10년 전 조회 1,189
10년 전 조회 1,199
10년 전 조회 1,165
10년 전 조회 1,234
10년 전 조회 1,163
10년 전 조회 1,257
10년 전 조회 1,338
10년 전 조회 1,316
10년 전 조회 1,266
10년 전 조회 1,182
10년 전 조회 1,301
10년 전 조회 1,205
10년 전 조회 1,224
10년 전 조회 1,187
10년 전 조회 1,154
10년 전 조회 1,162
10년 전 조회 1,174
10년 전 조회 1,265
10년 전 조회 1,203
10년 전 조회 1,287
10년 전 조회 1,192
10년 전 조회 1,223
10년 전 조회 1,220
10년 전 조회 1,267
10년 전 조회 1,360
10년 전 조회 1,441