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

· 9년 전 · 565

<?

// 퀵 정렬(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년 전 조회 624
9년 전 조회 624
9년 전 조회 759
9년 전 조회 578
9년 전 조회 700
9년 전 조회 541
9년 전 조회 602
9년 전 조회 483
9년 전 조회 673
9년 전 조회 562
9년 전 조회 573
9년 전 조회 618
9년 전 조회 577
9년 전 조회 580
9년 전 조회 536
9년 전 조회 917
9년 전 조회 972
9년 전 조회 949
9년 전 조회 875
9년 전 조회 662
9년 전 조회 845
9년 전 조회 955
9년 전 조회 644
9년 전 조회 946
9년 전 조회 905
9년 전 조회 1,304
9년 전 조회 916
9년 전 조회 1,107
9년 전 조회 769
9년 전 조회 895
9년 전 조회 655
9년 전 조회 638
9년 전 조회 762
9년 전 조회 727
9년 전 조회 895
9년 전 조회 627
9년 전 조회 704
9년 전 조회 653
9년 전 조회 591
9년 전 조회 677
9년 전 조회 544
9년 전 조회 583
9년 전 조회 531
9년 전 조회 597
9년 전 조회 581
9년 전 조회 1,032
9년 전 조회 550
9년 전 조회 481
9년 전 조회 745
9년 전 조회 566
9년 전 조회 559
9년 전 조회 524
9년 전 조회 501
9년 전 조회 450
9년 전 조회 425
9년 전 조회 504
9년 전 조회 519
9년 전 조회 457
9년 전 조회 404
9년 전 조회 508
9년 전 조회 450
9년 전 조회 477
9년 전 조회 515
9년 전 조회 537
9년 전 조회 431
9년 전 조회 474
9년 전 조회 534
9년 전 조회 468
9년 전 조회 572
9년 전 조회 510
9년 전 조회 445
9년 전 조회 408
9년 전 조회 458
9년 전 조회 398
10년 전 조회 443
10년 전 조회 474
10년 전 조회 403
10년 전 조회 459
10년 전 조회 416
10년 전 조회 522
10년 전 조회 623
10년 전 조회 578
10년 전 조회 532
10년 전 조회 458
10년 전 조회 550
10년 전 조회 466
10년 전 조회 500
10년 전 조회 457
10년 전 조회 432
10년 전 조회 435
10년 전 조회 462
10년 전 조회 534
10년 전 조회 484
10년 전 조회 544
10년 전 조회 465
10년 전 조회 475
10년 전 조회 476
10년 전 조회 506
10년 전 조회 600
10년 전 조회 699
🐛 버그신고