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

· 9년 전 · 400

<?

// 퀵 정렬(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년 전 조회 475
9년 전 조회 475
9년 전 조회 621
9년 전 조회 432
9년 전 조회 563
9년 전 조회 406
9년 전 조회 442
9년 전 조회 350
9년 전 조회 548
9년 전 조회 426
9년 전 조회 439
9년 전 조회 476
9년 전 조회 435
9년 전 조회 433
9년 전 조회 390
9년 전 조회 778
9년 전 조회 831
9년 전 조회 796
9년 전 조회 724
9년 전 조회 508
9년 전 조회 693
9년 전 조회 803
9년 전 조회 498
9년 전 조회 787
9년 전 조회 751
9년 전 조회 1,150
9년 전 조회 759
9년 전 조회 958
9년 전 조회 630
9년 전 조회 740
9년 전 조회 519
9년 전 조회 484
9년 전 조회 611
9년 전 조회 579
9년 전 조회 763
9년 전 조회 473
9년 전 조회 555
9년 전 조회 509
9년 전 조회 447
9년 전 조회 521
9년 전 조회 401
9년 전 조회 429
9년 전 조회 393
9년 전 조회 436
9년 전 조회 428
9년 전 조회 873
9년 전 조회 393
9년 전 조회 329
9년 전 조회 593
9년 전 조회 401
9년 전 조회 422
9년 전 조회 372
9년 전 조회 350
9년 전 조회 302
9년 전 조회 292
9년 전 조회 345
9년 전 조회 365
9년 전 조회 303
9년 전 조회 246
9년 전 조회 358
9년 전 조회 298
9년 전 조회 325
9년 전 조회 337
9년 전 조회 379
9년 전 조회 266
9년 전 조회 308
9년 전 조회 374
9년 전 조회 296
9년 전 조회 412
9년 전 조회 346
9년 전 조회 278
9년 전 조회 250
9년 전 조회 297
9년 전 조회 244
9년 전 조회 283
9년 전 조회 307
9년 전 조회 246
9년 전 조회 303
9년 전 조회 262
9년 전 조회 376
9년 전 조회 461
10년 전 조회 419
10년 전 조회 368
10년 전 조회 324
10년 전 조회 374
10년 전 조회 316
10년 전 조회 345
10년 전 조회 299
10년 전 조회 267
10년 전 조회 276
10년 전 조회 308
10년 전 조회 367
10년 전 조회 334
10년 전 조회 386
10년 전 조회 310
10년 전 조회 306
10년 전 조회 310
10년 전 조회 342
10년 전 조회 433
10년 전 조회 539
🐛 버그신고