ಇನ್ಸರ್ಷನ್ ಸಾರ್ಟ್ ಎಡಗಡೆ ಈಗಾಗಲೇ ಕ್ರಮದಲ್ಲಿರುವ ಭಾಗಕ್ಕೆ ಒಂದೊಂದೇ ಮೌಲ್ಯವನ್ನು ಸೇರಿಸುತ್ತದೆ. ದೊಡ್ಡ ಮೌಲ್ಯಗಳನ್ನು ಒಂದೊಂದು ಸ್ಥಾನ ಬಲಕ್ಕೆ ಸರಿಸಿ, ಖಾಲಿಯಾದ ಜಾಗದಲ್ಲಿ ಮುಂದಿನ ಮೌಲ್ಯವನ್ನು ಇಡುತ್ತದೆ. ಪಟ್ಟಿ ಮೊದಲೇ ಕ್ರಮದಲ್ಲಿದ್ದರೆ ಸಮಯ Θ(n). ಮೌಲ್ಯಗಳು ಯಾದೃಚ್ಛಿಕ ಕ್ರಮದಲ್ಲಿದ್ದರೆ ಸರಾಸರಿ ಸಮಯ Θ(n²). ಪೂರ್ತಿ ಹಿಮ್ಮುಖ ಕ್ರಮದಲ್ಲಿದ್ದರೆ ಅತಿ ಹೆಚ್ಚು ಸಮಯ ಬೇಕು. ಆಗಲೂ ಸಮಯ ಪಟ್ಟಿಯ ಉದ್ದದ ವರ್ಗಕ್ಕೆ ಅನುಗುಣವಾಗಿ ಬೆಳೆಯುತ್ತದೆ.
ಒಂದು ಸರಳ ಉದಾಹರಣೆ
3ರ ಮೊದಲು 1 ಸೇರಿಸಿ. ನಂತರ 2 ಸೇರಿಸಲು 3 ಅನ್ನು ಮತ್ತೊಮ್ಮೆ ಪಕ್ಕಕ್ಕೆ ಸರಿಸಿ. ಈಗ ಸಂಖ್ಯೆಗಳನ್ನು ಚಿಕ್ಕದರಿಂದ ದೊಡ್ಡದಕ್ಕೆ ಪರದೆಯ ಮೇಲೆ ತೋರಿಸಿ.
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
ಜಾಹೀರಾತುಗಳು
ಉದಾಹರಣೆಯನ್ನು ಹಂತ ಹಂತವಾಗಿ ನೋಡಿ
[15, 3, 12, 6, -9, 9, 0] ಇಂದ ಆರಂಭಿಸಿ.
15 ರಿಂದ ಆರಂಭಿಸಿ. ಮುಂದಿನ ಮೌಲ್ಯವನ್ನು ಉಳಿಸು, ೩.
೧೫ನ್ನು ಒಂದು ಸ್ಥಾನ ಬಲಕ್ಕೆ ಸರಿಸಿ ಮತ್ತು ೩ನ್ನು ಆರಂಭದಲ್ಲಿ ಸೇರಿಸಿ. ಪೂರ್ವಪ್ರತ್ಯಯವು ಈಗ [೩, ೧೫] ಆಗಿದೆ.
ಉಳಿದ ಪ್ರತಿಯೊಂದು ಮೌಲ್ಯಕ್ಕೆ, ಅದು ಸೇರಿಸುವ ಮೊದಲು ಕೇವಲ ದೊಡ್ಡ ಮೌಲ್ಯಗಳನ್ನು ಬದಲಾಯಿಸುವುದು. ಸಮಾನ ಮೌಲ್ಯಗಳು ಅವುಗಳ ಮೂಲ ಕ್ರಮವನ್ನು ಕಾಪಾಡಿಕೊಳ್ಳುತ್ತವೆ.
PHP ಭಾಷೆಯಲ್ಲಿ ಇನ್ಸರ್ಶನ್ ಸಾರ್ಟ್ ಹಂತ ಹಂತವಾಗಿ
PHP ಮೂಲ ಕೋಡ್
<?php
class InsertionSortExample {
public function insertionSort(&$arr) {
// Un-sorted array from position 1 to length -1
for($i = 1; $i < sizeof($arr); $i++) {
// Take the left most item in an un-sorted array to temp variable
$temp = $arr[$i];
// Mark the left most position as empty or hole
$holePosition = $i;
// Traverse the sorted array from right to left direction
// Move the item from the sorted array to the empty position (i.e. holePosition) only if the temp variable is less then
// Mark the current item's position as empty by decrementing the value by one
while($holePosition > 0 && $arr[$holePosition - 1] > $temp) {
$arr[$holePosition] = $arr[$holePosition - 1];
$holePosition--;
}
// Once the comparison done, move the value in temp variable to the lastly marked empty position
$arr[$holePosition] = $temp;
}
}
public function printArray(&$arr) {
// Loop the item and print each item in the console with white space seperated
for($i = 0; $i < sizeof($arr); $i++) {
echo($arr[$i] . " ");
}
echo("\n");
}
}
$obj = new InsertionSortExample();
$arr = array();
array_push($arr, 15, 3, 12, 6, -9, 9, 0);
echo("Before Sorting: ");
$obj->printArray($arr);
$obj->insertionSort($arr);
echo("After Sorting: ");
$obj->printArray($arr);
ಫಲಿತಾಂಶ
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15