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

· 10년 전 · 1446

<?

// 퀵 정렬(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,578
10년 전 조회 1,611
10년 전 조회 1,736
10년 전 조회 1,583
10년 전 조회 1,698
10년 전 조회 1,505
10년 전 조회 1,593
10년 전 조회 1,408
10년 전 조회 1,630
10년 전 조회 1,428
10년 전 조회 1,474
10년 전 조회 1,580
10년 전 조회 1,485
10년 전 조회 1,516
10년 전 조회 1,445
10년 전 조회 1,859
10년 전 조회 1,883
10년 전 조회 1,861
10년 전 조회 1,828
10년 전 조회 1,607
10년 전 조회 1,733
10년 전 조회 1,902
10년 전 조회 1,610
10년 전 조회 1,882
10년 전 조회 1,866
10년 전 조회 2,239
10년 전 조회 1,846
10년 전 조회 2,052
10년 전 조회 1,684
10년 전 조회 1,831
10년 전 조회 1,536
10년 전 조회 1,606
10년 전 조회 1,654
10년 전 조회 1,645
10년 전 조회 1,813
10년 전 조회 1,579
10년 전 조회 1,604
10년 전 조회 1,615
10년 전 조회 1,524
10년 전 조회 1,583
10년 전 조회 1,397
10년 전 조회 1,472
10년 전 조회 1,381
10년 전 조회 1,541
10년 전 조회 1,478
10년 전 조회 1,947
10년 전 조회 1,414
10년 전 조회 1,393
10년 전 조회 1,647
10년 전 조회 1,447
10년 전 조회 1,422
10년 전 조회 1,426
10년 전 조회 1,372
10년 전 조회 1,307
10년 전 조회 1,282
10년 전 조회 1,399
10년 전 조회 1,365
10년 전 조회 1,319
10년 전 조회 1,205
10년 전 조회 1,293
10년 전 조회 1,280
10년 전 조회 1,306
10년 전 조회 1,351
10년 전 조회 1,347
10년 전 조회 1,295
10년 전 조회 1,294
10년 전 조회 1,330
10년 전 조회 1,311
10년 전 조회 1,389
10년 전 조회 1,304
10년 전 조회 1,254
10년 전 조회 1,238
10년 전 조회 1,255
10년 전 조회 1,263
10년 전 조회 1,263
10년 전 조회 1,281
10년 전 조회 1,231
10년 전 조회 1,295
10년 전 조회 1,226
10년 전 조회 1,326
10년 전 조회 1,418
10년 전 조회 1,385
10년 전 조회 1,322
10년 전 조회 1,245
10년 전 조회 1,367
10년 전 조회 1,265
10년 전 조회 1,309
10년 전 조회 1,257
10년 전 조회 1,221
10년 전 조회 1,220
10년 전 조회 1,244
10년 전 조회 1,320
10년 전 조회 1,274
10년 전 조회 1,354
10년 전 조회 1,262
10년 전 조회 1,301
10년 전 조회 1,287
10년 전 조회 1,348
10년 전 조회 1,434
10년 전 조회 1,501