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

· 10년 전 · 1346

<?

// 퀵 정렬(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,510
10년 전 조회 1,519
10년 전 조회 1,650
10년 전 조회 1,503
10년 전 조회 1,608
10년 전 조회 1,433
10년 전 조회 1,512
10년 전 조회 1,336
10년 전 조회 1,557
10년 전 조회 1,367
10년 전 조회 1,398
10년 전 조회 1,504
10년 전 조회 1,403
10년 전 조회 1,435
10년 전 조회 1,364
10년 전 조회 1,778
10년 전 조회 1,812
10년 전 조회 1,775
10년 전 조회 1,734
10년 전 조회 1,514
10년 전 조회 1,650
10년 전 조회 1,806
10년 전 조회 1,515
10년 전 조회 1,811
10년 전 조회 1,764
10년 전 조회 2,153
10년 전 조회 1,761
10년 전 조회 1,964
10년 전 조회 1,598
10년 전 조회 1,730
10년 전 조회 1,447
10년 전 조회 1,509
10년 전 조회 1,572
10년 전 조회 1,562
10년 전 조회 1,709
10년 전 조회 1,475
10년 전 조회 1,509
10년 전 조회 1,477
10년 전 조회 1,416
10년 전 조회 1,481
10년 전 조회 1,298
10년 전 조회 1,369
10년 전 조회 1,278
10년 전 조회 1,414
10년 전 조회 1,362
10년 전 조회 1,839
10년 전 조회 1,309
10년 전 조회 1,280
10년 전 조회 1,540
10년 전 조회 1,347
10년 전 조회 1,322
10년 전 조회 1,328
10년 전 조회 1,264
10년 전 조회 1,194
10년 전 조회 1,176
10년 전 조회 1,275
10년 전 조회 1,271
10년 전 조회 1,202
10년 전 조회 1,103
10년 전 조회 1,184
10년 전 조회 1,158
10년 전 조회 1,181
10년 전 조회 1,238
10년 전 조회 1,237
10년 전 조회 1,172
10년 전 조회 1,179
10년 전 조회 1,224
10년 전 조회 1,196
10년 전 조회 1,269
10년 전 조회 1,194
10년 전 조회 1,139
10년 전 조회 1,119
10년 전 조회 1,147
10년 전 조회 1,119
10년 전 조회 1,149
10년 전 조회 1,163
10년 전 조회 1,135
10년 전 조회 1,188
10년 전 조회 1,130
10년 전 조회 1,218
10년 전 조회 1,312
10년 전 조회 1,278
10년 전 조회 1,222
10년 전 조회 1,149
10년 전 조회 1,258
10년 전 조회 1,176
10년 전 조회 1,189
10년 전 조회 1,153
10년 전 조회 1,127
10년 전 조회 1,129
10년 전 조회 1,146
10년 전 조회 1,238
10년 전 조회 1,186
10년 전 조회 1,265
10년 전 조회 1,163
10년 전 조회 1,194
10년 전 조회 1,174
10년 전 조회 1,235
10년 전 조회 1,334
10년 전 조회 1,413