insertion sort
VD:
A={586310}
Insertion sort lam nhu sau :
Chia mang A lam 2 phan sorted va unsorted
Ban dau sorted la B= { 5 }
Unsorted la C= { 863 10 }
Lần làm thứ nhất :
Lay phan tu dau tien của C là 8 ra -> C= { 63 10}
Tim vi tri cua so 8 trong mang B -> B= { 5 8 }
Lân làm thứ hai :
Lay phan tu dau tiên của C là 6 ra -> C = { 3 10 }
Tim vị trí của sô 6 trong mang B -> B= {568}
Lân làm thứ ba :
Lay phan tu dau tien của C là 3 ra -> C = { 10 }
Tim vi tri cua s6 3 trong mang B -> B= {3568}
Lân làm thứ tư :
Lay phan tu dau tien cua C la 10 ra -> C= { }
Tìm vị trí của sô 10 trong mang B -> B= {3 5 6 8 10}
Kết thúc thuật toán
Ý nghĩa của insertion sort là lấy một phần tử của mảng ra và insert vào vị trí thích hợp trong mảng Giải thuật
Code:
void Sortable _List<Record>::insertion_sort() // phien ban nay list duoc hien thuc thong qua mang chứ kg phải con trỏ
{
int first_unsorted ;
int position ;
Record current ;
for( first_unsorted = 1 ; first_unsorted < count ; first_ unsorted ++)
{
if(entry|first_ unsorted] < entry[first_unsorted-1])
{
position = first_unsorted ; current = entry[first_unsorted] ;
do {
entry[position] = entry [ position -1] ; position ;
Trang 2} while (position > 0 && entry[position-1]> current ); entry[position] = current ;