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

· 9년 전 · 603

<?

// 퀵 정렬(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년 전 조회 646
9년 전 조회 657
9년 전 조회 789
9년 전 조회 623
9년 전 조회 750
9년 전 조회 555
9년 전 조회 618
9년 전 조회 501
9년 전 조회 692
9년 전 조회 582
9년 전 조회 589
9년 전 조회 642
9년 전 조회 595
9년 전 조회 603
9년 전 조회 576
9년 전 조회 946
9년 전 조회 996
9년 전 조회 966
9년 전 조회 921
9년 전 조회 695
9년 전 조회 866
9년 전 조회 987
9년 전 조회 688
9년 전 조회 971
9년 전 조회 932
9년 전 조회 1,352
9년 전 조회 963
9년 전 조회 1,127
9년 전 조회 800
9년 전 조회 937
9년 전 조회 677
9년 전 조회 666
9년 전 조회 787
9년 전 조회 757
9년 전 조회 931
9년 전 조회 653
9년 전 조회 723
9년 전 조회 695
9년 전 조회 610
9년 전 조회 708
9년 전 조회 562
9년 전 조회 605
9년 전 조회 549
9년 전 조회 637
9년 전 조회 618
9년 전 조회 1,070
9년 전 조회 578
9년 전 조회 506
9년 전 조회 772
9년 전 조회 604
9년 전 조회 580
10년 전 조회 554
10년 전 조회 527
10년 전 조회 470
10년 전 조회 446
10년 전 조회 522
10년 전 조회 538
10년 전 조회 491
10년 전 조회 435
10년 전 조회 522
10년 전 조회 497
10년 전 조회 500
10년 전 조회 561
10년 전 조회 574
10년 전 조회 465
10년 전 조회 497
10년 전 조회 564
10년 전 조회 505
10년 전 조회 591
10년 전 조회 530
10년 전 조회 476
10년 전 조회 431
10년 전 조회 479
10년 전 조회 441
10년 전 조회 464
10년 전 조회 498
10년 전 조회 433
10년 전 조회 479
10년 전 조회 444
10년 전 조회 544
10년 전 조회 643
10년 전 조회 604
10년 전 조회 555
10년 전 조회 489
10년 전 조회 583
10년 전 조회 491
10년 전 조회 525
10년 전 조회 474
10년 전 조회 453
10년 전 조회 452
10년 전 조회 485
10년 전 조회 548
10년 전 조회 504
10년 전 조회 578
10년 전 조회 488
10년 전 조회 518
10년 전 조회 494
10년 전 조회 554
10년 전 조회 635
10년 전 조회 728
🐛 버그신고