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

· 10년 전 · 1612

<?

// 퀵 정렬(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,758
10년 전 조회 1,786
10년 전 조회 1,894
10년 전 조회 1,752
10년 전 조회 1,882
10년 전 조회 1,649
10년 전 조회 1,760
10년 전 조회 1,541
10년 전 조회 1,785
10년 전 조회 1,561
10년 전 조회 1,631
10년 전 조회 1,734
10년 전 조회 1,626
10년 전 조회 1,657
10년 전 조회 1,615
10년 전 조회 2,018
10년 전 조회 2,025
10년 전 조회 2,013
10년 전 조회 1,985
10년 전 조회 1,759
10년 전 조회 1,881
10년 전 조회 2,042
10년 전 조회 1,746
10년 전 조회 2,035
10년 전 조회 1,995
10년 전 조회 2,381
10년 전 조회 1,991
10년 전 조회 2,207
10년 전 조회 1,813
10년 전 조회 1,968
10년 전 조회 1,665
10년 전 조회 1,751
10년 전 조회 1,787
10년 전 조회 1,798
10년 전 조회 1,955
10년 전 조회 1,723
10년 전 조회 1,756
10년 전 조회 1,770
10년 전 조회 1,674
10년 전 조회 1,726
10년 전 조회 1,536
10년 전 조회 1,611
10년 전 조회 1,529
10년 전 조회 1,684
10년 전 조회 1,632
10년 전 조회 2,100
10년 전 조회 1,573
10년 전 조회 1,535
10년 전 조회 1,799
10년 전 조회 1,613
10년 전 조회 1,569
10년 전 조회 1,575
10년 전 조회 1,544
10년 전 조회 1,458
10년 전 조회 1,434
10년 전 조회 1,548
10년 전 조회 1,519
10년 전 조회 1,475
10년 전 조회 1,368
10년 전 조회 1,438
10년 전 조회 1,476
10년 전 조회 1,456
10년 전 조회 1,527
10년 전 조회 1,494
10년 전 조회 1,460
10년 전 조회 1,451
10년 전 조회 1,498
10년 전 조회 1,469
10년 전 조회 1,555
10년 전 조회 1,459
10년 전 조회 1,415
10년 전 조회 1,387
10년 전 조회 1,413
10년 전 조회 1,435
10년 전 조회 1,426
10년 전 조회 1,454
10년 전 조회 1,391
10년 전 조회 1,469
10년 전 조회 1,405
10년 전 조회 1,492
10년 전 조회 1,580
10년 전 조회 1,562
10년 전 조회 1,487
10년 전 조회 1,410
10년 전 조회 1,554
10년 전 조회 1,452
10년 전 조회 1,483
10년 전 조회 1,429
10년 전 조회 1,417
10년 전 조회 1,408
10년 전 조회 1,435
10년 전 조회 1,533
10년 전 조회 1,453
10년 전 조회 1,541
10년 전 조회 1,442
10년 전 조회 1,508
10년 전 조회 1,498
10년 전 조회 1,550
10년 전 조회 1,617
10년 전 조회 1,693