MOT SO GIAI THUAT SAP XEP rất bổ ích
Trang 1Sắp xếp mảng
= Sap xếp liên quan đến việc thay đối vị trí các phân tử
theo thứ tự xácđịnh như tăng dân hay giảm dân
" Dữ liệu trong mang sẽ dé dang tim thay hơn nếu mảng được sắp xếp
= Hai phương pháp sắp xếp mảng được trinh bay: Bubble Sort va Insertion Sort
= Trong phương pháp Bubble sort, việc so sánh bắt đâu từ phân tử dưới cùng và phân tử có giá trị nhỏ hơn sẽ
chuyền dân lên trên (nối bot)
“ Trong phương pháp Insertion sort, mỗi phân tử trong
máng được xem xét, và đặt vào vị trí đúng của nó giữa các phân tử đã được sắp xếp
Trang 2Bubble Sort
2s
23
CK 16
16
25
23
23
CK 25
16
25
2
16
23
16
23
16 16
23 23
Chee 25
16
23
25
C Cha
23
23
23
25
25 25
23
16
23
25
25
16
23
25
Trang 3
Bubble Sort - tt
#include <stdio.h>
void main() {
int i1,j,temp,arr num[5]={23,90,9,25,16};
clrscr ();
/* Compares elements */
1£ (arr num[J]<arr num[3J-1])
{ temp=arr num[j];
arr num[j]=arr num[j-1]; arr num[j-1]=temp;
Trang 4Bubble Sort - tt
printf("\nThe sorted array");
for(i=0;i<57i++)
printf("\n%d", arr_num[i]);
getch();
Trang 5
23
Insertion Sort
90
23
9
23
90
90
25
25
16
25
16 16
23
90
23
25
90
16
25
16
25
9
23
90
25
16
9
23
25
90
16 —
TT7 Sic 5 of 23
—|olnl
Trang 6
Insertion Sort - tt
#include<stdio.h>
char flag;
/*Loop to compare each element of the unsorted part of the array*/
/*Loop for each element in the sorted part of the array*/
/*Invoke the function to insert the number*/
flag='y';
}
}
for (i=0; i<5; itt)
printf ("Sd\t", arr[i]);
getch () ;
Trang 7Insertion Sort-3
insertnum(int arrnum[], int x, int y) {
int temp;
/*Store the number to be inserted*/
temp=arrnum [x] ;
/*Loop to push the sorted part of the
array down from the position where the number
has to inserted*/
for(;x>y; x ) arrnum[x]=arrnum[x-1] ;
/*Insert the number*/
arrnum[x]=temp;