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

· 10년 전 · 1417

<?

// 퀵 정렬(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,565
10년 전 조회 1,580
10년 전 조회 1,711
10년 전 조회 1,566
10년 전 조회 1,667
10년 전 조회 1,485
10년 전 조회 1,568
10년 전 조회 1,386
10년 전 조회 1,609
10년 전 조회 1,410
10년 전 조회 1,453
10년 전 조회 1,561
10년 전 조회 1,463
10년 전 조회 1,498
10년 전 조회 1,426
10년 전 조회 1,839
10년 전 조회 1,866
10년 전 조회 1,842
10년 전 조회 1,800
10년 전 조회 1,579
10년 전 조회 1,705
10년 전 조회 1,874
10년 전 조회 1,588
10년 전 조회 1,862
10년 전 조회 1,847
10년 전 조회 2,218
10년 전 조회 1,821
10년 전 조회 2,029
10년 전 조회 1,663
10년 전 조회 1,810
10년 전 조회 1,512
10년 전 조회 1,576
10년 전 조회 1,633
10년 전 조회 1,614
10년 전 조회 1,780
10년 전 조회 1,550
10년 전 조회 1,581
10년 전 조회 1,582
10년 전 조회 1,497
10년 전 조회 1,556
10년 전 조회 1,368
10년 전 조회 1,447
10년 전 조회 1,342
10년 전 조회 1,504
10년 전 조회 1,450
10년 전 조회 1,923
10년 전 조회 1,385
10년 전 조회 1,353
10년 전 조회 1,614
10년 전 조회 1,418
10년 전 조회 1,395
10년 전 조회 1,386
10년 전 조회 1,337
10년 전 조회 1,266
10년 전 조회 1,243
10년 전 조회 1,360
10년 전 조회 1,333
10년 전 조회 1,284
10년 전 조회 1,176
10년 전 조회 1,255
10년 전 조회 1,234
10년 전 조회 1,257
10년 전 조회 1,311
10년 전 조회 1,310
10년 전 조회 1,258
10년 전 조회 1,251
10년 전 조회 1,295
10년 전 조회 1,274
10년 전 조회 1,350
10년 전 조회 1,260
10년 전 조회 1,213
10년 전 조회 1,201
10년 전 조회 1,212
10년 전 조회 1,207
10년 전 조회 1,221
10년 전 조회 1,233
10년 전 조회 1,192
10년 전 조회 1,255
10년 전 조회 1,196
10년 전 조회 1,288
10년 전 조회 1,372
10년 전 조회 1,347
10년 전 조회 1,288
10년 전 조회 1,206
10년 전 조회 1,336
10년 전 조회 1,224
10년 전 조회 1,262
10년 전 조회 1,221
10년 전 조회 1,183
10년 전 조회 1,184
10년 전 조회 1,204
10년 전 조회 1,295
10년 전 조회 1,231
10년 전 조회 1,321
10년 전 조회 1,224
10년 전 조회 1,263
10년 전 조회 1,253
10년 전 조회 1,296
10년 전 조회 1,394
10년 전 조회 1,468