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

· 9년 전 · 589

<?

// 퀵 정렬(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);

?>

|
댓글을 작성하시려면 로그인이 필요합니다. 로그인

프로그램

+
제목 글쓴이 날짜 조회
9년 전 조회 640
9년 전 조회 650
9년 전 조회 779
9년 전 조회 615
9년 전 조회 737
9년 전 조회 554
9년 전 조회 615
9년 전 조회 500
9년 전 조회 688
9년 전 조회 582
9년 전 조회 585
9년 전 조회 637
9년 전 조회 589
9년 전 조회 598
9년 전 조회 568
9년 전 조회 937
9년 전 조회 993
9년 전 조회 961
9년 전 조회 912
9년 전 조회 686
9년 전 조회 865
9년 전 조회 976
9년 전 조회 685
9년 전 조회 964
9년 전 조회 926
9년 전 조회 1,340
9년 전 조회 953
9년 전 조회 1,121
9년 전 조회 796
9년 전 조회 931
9년 전 조회 670
9년 전 조회 658
9년 전 조회 779
9년 전 조회 746
9년 전 조회 923
9년 전 조회 645
9년 전 조회 718
9년 전 조회 685
9년 전 조회 607
9년 전 조회 697
9년 전 조회 558
9년 전 조회 597
9년 전 조회 542
9년 전 조회 626
9년 전 조회 602
9년 전 조회 1,061
9년 전 조회 574
9년 전 조회 500
9년 전 조회 767
9년 전 조회 590
9년 전 조회 575
9년 전 조회 546
9년 전 조회 518
9년 전 조회 461
9년 전 조회 442
10년 전 조회 520
10년 전 조회 534
10년 전 조회 478
10년 전 조회 423
10년 전 조회 522
10년 전 조회 488
10년 전 조회 494
10년 전 조회 549
10년 전 조회 562
10년 전 조회 451
10년 전 조회 489
10년 전 조회 560
10년 전 조회 492
10년 전 조회 587
10년 전 조회 525
10년 전 조회 468
10년 전 조회 427
10년 전 조회 471
10년 전 조회 430
10년 전 조회 456
10년 전 조회 490
10년 전 조회 426
10년 전 조회 476
10년 전 조회 434
10년 전 조회 539
10년 전 조회 636
10년 전 조회 595
10년 전 조회 553
10년 전 조회 481
10년 전 조회 574
10년 전 조회 483
10년 전 조회 520
10년 전 조회 467
10년 전 조회 447
10년 전 조회 448
10년 전 조회 480
10년 전 조회 544
10년 전 조회 499
10년 전 조회 569
10년 전 조회 481
10년 전 조회 503
10년 전 조회 489
10년 전 조회 544
10년 전 조회 624
10년 전 조회 718
🐛 버그신고