ประเภทของการเรียงลำดับ
C มีเทคนิคเรียงลำดับ 5 แบบ:
- Bubble Sort (หรือ Exchange Sort)
- Selection Sort
- Insertion Sort (หรือ Linear Sort)
- Quick Sort (หรือ Partition Exchange Sort)
- Merge Sort (หรือ External Sort)
Insertion Sort
ตรรกะการเรียงด้วย Insertion Sort:
for(i = 1; i <= n - 1; i++) {
for(j = i; j > 0 && a[j - 1] > a[j]; j--) {
t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}คำอธิบาย
พิจารณาองค์ประกอบที่ไม่เรียงลำดับ (รูปภาพไม่ได้รวม)
ตัวอย่างโค้ด
#include <stdio.h>
int main() {
int a[50], i, j, n, t;
printf("enter the No: of elements in the list:\n");
scanf("%d", &n);
printf("enter the elements:\n");
for(i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for(i = 1; i <= n - 1; i++) {
for(j = i; j > 0 && a[j - 1] > a[j]; j--) {
t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}
printf("after insertion sorting the elements are:\n");
for(i = 0; i < n; i++)
printf("%d\t", a[i]);
return 0;
}ผลลัพธ์
Enter the No: of elements in the list: 10 Enter the elements: 34 125 2 6 78 49 1 3 89 23 After insertion sorting the elements are: 1 2 3 6 23 34 49 78 89 125