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

· 10년 전 · 1379

<?

// 퀵 정렬(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,533
10년 전 조회 1,547
10년 전 조회 1,683
10년 전 조회 1,530
10년 전 조회 1,628
10년 전 조회 1,462
10년 전 조회 1,543
10년 전 조회 1,363
10년 전 조회 1,585
10년 전 조회 1,392
10년 전 조회 1,426
10년 전 조회 1,537
10년 전 조회 1,433
10년 전 조회 1,470
10년 전 조회 1,401
10년 전 조회 1,813
10년 전 조회 1,839
10년 전 조회 1,809
10년 전 조회 1,768
10년 전 조회 1,546
10년 전 조회 1,679
10년 전 조회 1,848
10년 전 조회 1,560
10년 전 조회 1,842
10년 전 조회 1,815
10년 전 조회 2,192
10년 전 조회 1,799
10년 전 조회 1,996
10년 전 조회 1,635
10년 전 조회 1,774
10년 전 조회 1,481
10년 전 조회 1,544
10년 전 조회 1,603
10년 전 조회 1,587
10년 전 조회 1,741
10년 전 조회 1,514
10년 전 조회 1,545
10년 전 조회 1,528
10년 전 조회 1,450
10년 전 조회 1,523
10년 전 조회 1,334
10년 전 조회 1,403
10년 전 조회 1,314
10년 전 조회 1,465
10년 전 조회 1,403
10년 전 조회 1,884
10년 전 조회 1,349
10년 전 조회 1,311
10년 전 조회 1,574
10년 전 조회 1,380
10년 전 조회 1,359
10년 전 조회 1,354
10년 전 조회 1,297
10년 전 조회 1,230
10년 전 조회 1,205
10년 전 조회 1,308
10년 전 조회 1,303
10년 전 조회 1,242
10년 전 조회 1,132
10년 전 조회 1,215
10년 전 조회 1,202
10년 전 조회 1,210
10년 전 조회 1,267
10년 전 조회 1,271
10년 전 조회 1,208
10년 전 조회 1,211
10년 전 조회 1,253
10년 전 조회 1,226
10년 전 조회 1,312
10년 전 조회 1,221
10년 전 조회 1,176
10년 전 조회 1,159
10년 전 조회 1,170
10년 전 조회 1,155
10년 전 조회 1,181
10년 전 조회 1,193
10년 전 조회 1,162
10년 전 조회 1,228
10년 전 조회 1,158
10년 전 조회 1,250
10년 전 조회 1,333
10년 전 조회 1,313
10년 전 조회 1,256
10년 전 조회 1,173
10년 전 조회 1,293
10년 전 조회 1,199
10년 전 조회 1,218
10년 전 조회 1,181
10년 전 조회 1,146
10년 전 조회 1,150
10년 전 조회 1,167
10년 전 조회 1,260
10년 전 조회 1,200
10년 전 조회 1,278
10년 전 조회 1,184
10년 전 조회 1,214
10년 전 조회 1,208
10년 전 조회 1,261
10년 전 조회 1,355
10년 전 조회 1,430