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

· 9년 전 · 544

<?

// 퀵 정렬(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년 전 조회 611
9년 전 조회 606
9년 전 조회 740
9년 전 조회 567
9년 전 조회 686
9년 전 조회 523
9년 전 조회 576
9년 전 조회 459
9년 전 조회 661
9년 전 조회 547
9년 전 조회 560
9년 전 조회 602
9년 전 조회 560
9년 전 조회 568
9년 전 조회 520
9년 전 조회 907
9년 전 조회 949
9년 전 조회 935
9년 전 조회 858
9년 전 조회 651
9년 전 조회 830
9년 전 조회 943
9년 전 조회 634
9년 전 조회 932
9년 전 조회 888
9년 전 조회 1,284
9년 전 조회 904
9년 전 조회 1,090
9년 전 조회 748
9년 전 조회 878
9년 전 조회 634
9년 전 조회 626
9년 전 조회 750
9년 전 조회 718
9년 전 조회 887
9년 전 조회 609
9년 전 조회 690
9년 전 조회 633
9년 전 조회 572
9년 전 조회 665
9년 전 조회 526
9년 전 조회 567
9년 전 조회 519
9년 전 조회 581
9년 전 조회 566
9년 전 조회 1,018
9년 전 조회 536
9년 전 조회 468
9년 전 조회 732
9년 전 조회 545
9년 전 조회 542
9년 전 조회 509
9년 전 조회 485
9년 전 조회 437
9년 전 조회 415
9년 전 조회 488
9년 전 조회 502
9년 전 조회 446
9년 전 조회 387
9년 전 조회 492
9년 전 조회 434
9년 전 조회 465
9년 전 조회 497
9년 전 조회 525
9년 전 조회 418
9년 전 조회 459
9년 전 조회 519
9년 전 조회 450
9년 전 조회 559
9년 전 조회 496
9년 전 조회 427
9년 전 조회 394
9년 전 조회 446
9년 전 조회 382
9년 전 조회 431
9년 전 조회 460
9년 전 조회 391
10년 전 조회 440
10년 전 조회 402
10년 전 조회 507
10년 전 조회 606
10년 전 조회 565
10년 전 조회 516
10년 전 조회 444
10년 전 조회 532
10년 전 조회 452
10년 전 조회 488
10년 전 조회 434
10년 전 조회 412
10년 전 조회 413
10년 전 조회 450
10년 전 조회 515
10년 전 조회 467
10년 전 조회 533
10년 전 조회 445
10년 전 조회 461
10년 전 조회 459
10년 전 조회 494
10년 전 조회 586
10년 전 조회 682
🐛 버그신고