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

· 9년 전 · 446

<?

// 퀵 정렬(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년 전 조회 512
9년 전 조회 510
9년 전 조회 658
9년 전 조회 475
9년 전 조회 614
9년 전 조회 438
9년 전 조회 489
9년 전 조회 379
9년 전 조회 576
9년 전 조회 468
9년 전 조회 473
9년 전 조회 516
9년 전 조회 468
9년 전 조회 471
9년 전 조회 436
9년 전 조회 823
9년 전 조회 867
9년 전 조회 838
9년 전 조회 763
9년 전 조회 552
9년 전 조회 727
9년 전 조회 853
9년 전 조회 540
9년 전 조회 827
9년 전 조회 791
9년 전 조회 1,196
9년 전 조회 798
9년 전 조회 998
9년 전 조회 662
9년 전 조회 783
9년 전 조회 557
9년 전 조회 524
9년 전 조회 650
9년 전 조회 616
9년 전 조회 808
9년 전 조회 514
9년 전 조회 592
9년 전 조회 551
9년 전 조회 488
9년 전 조회 565
9년 전 조회 437
9년 전 조회 469
9년 전 조회 425
9년 전 조회 489
9년 전 조회 472
9년 전 조회 911
9년 전 조회 438
9년 전 조회 362
9년 전 조회 632
9년 전 조회 447
9년 전 조회 455
9년 전 조회 415
9년 전 조회 386
9년 전 조회 345
9년 전 조회 325
9년 전 조회 376
9년 전 조회 399
9년 전 조회 341
9년 전 조회 284
9년 전 조회 394
9년 전 조회 338
9년 전 조회 359
9년 전 조회 385
9년 전 조회 421
9년 전 조회 302
9년 전 조회 348
9년 전 조회 405
9년 전 조회 334
9년 전 조회 451
9년 전 조회 381
9년 전 조회 316
9년 전 조회 286
9년 전 조회 338
9년 전 조회 287
9년 전 조회 322
9년 전 조회 348
9년 전 조회 280
9년 전 조회 339
9년 전 조회 298
9년 전 조회 408
9년 전 조회 493
10년 전 조회 454
10년 전 조회 402
10년 전 조회 357
10년 전 조회 413
10년 전 조회 352
10년 전 조회 374
10년 전 조회 331
10년 전 조회 297
10년 전 조회 301
10년 전 조회 333
10년 전 조회 404
10년 전 조회 367
10년 전 조회 419
10년 전 조회 350
10년 전 조회 341
10년 전 조회 347
10년 전 조회 389
10년 전 조회 470
10년 전 조회 571
🐛 버그신고