يبني ترتيب الإدراج جزءًا مرتبًا على اليسار، ويضيف إليه قيمة واحدة كل مرة. حرّك القيم الأكبر خانة إلى اليمين وضع القيمة التالية في الفراغ. إذا كانت القيم مرتبة أصلًا فالزمن Θ(n). مع ترتيب عشوائي يكون متوسط الزمن Θ(n²). والترتيب المعكوس هو أسوأ حالة ويحتاج أيضًا إلى زمن تربيعي.
مثال بسيط
ضع 1 قبل 3، ثم أزِح 3 مرة أخرى لتضع 2 في مكانه. اعرض القيم المرتبة.
في البداية3 1 2
النتيجة1 2 3
lesson.c
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int values[] = {3, 1, 2};
int i = 1;
while (i < 3) {
int key = values[i];
int j = i - 1;
while ((j >= 0) && (values[j] > key)) {
values[j + 1] = values[j];
j -= 1;
}
values[j + 1] = key;
i += 1;
}
i = 0;
while (i < 3) {
printf("%d\n", values[i]);
i += 1;
}
}
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 أول جزء مرتب من القائمة. احفظ القيمة التالية وهي 3.
انقل 15 موضعاً واحداً إلى اليمين وضع 3 في البداية. أصبح الجزء المرتب [3, 15].
عند إدخال كل قيمة متبقية أزِح فقط القيم التي تكبرها. وهكذا تحتفظ القيم المتساوية بترتيبها الأصلي.
الترتيب بالإدراج بلغة C خطوة بخطوة
الكود المصدري بلغة C
#include<stdio.h>
void insertionSort(int arr[], size_t size) {
// Un-sorted array from position 1 to size -1
for(size_t i = 1; i < size; i++) {
// Take the left most item in an un-sorted array to temp variable
int temp = arr[i];
// Mark the left most position as empty or hole
int 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;
}
}
void printArray(const int arr[], size_t size) {
// Loop the item and print each item in the console with white space seperated
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
insertionSort(arr, SIZE);
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
المخرجات
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15