SẮP XẾP LIST THEO THỨ TỰ TĂNG DẦN
CẤU TRÚC DỮ LIỆU VÀ MỘT SỐ HÀM XÂY DỰNG
Code:
#include "conio.h"
#include "stdio.h"
#include "alloc.h"
typedef unsigned int Position;
typedef int ElementType;
typedef struct Node{
ElementType Element;
Node* Next;
};
typedef Node * List;
Node * Make_Node(ElementType x) {
Node * temp = (Node*)malloc(sizeof(Node));
temp->Element = x;
return temp;
}
List MakeNull_List() {
List temp = (List)malloc(sizeof(List));
temp->Next = NULL;
return temp;
}
char Empty_List(List L) {
return L->Next == NULL;
}
void Insert(List L, Node * p) {
p->Next = L->Next;
L->Next = p;
}
void Insert(List L, Node * p, Position i) {
List temp = L;
Position j = 1;
while(j<i && temp!=NULL) {
temp = temp->Next;
j++;
}
if(i==j)
Insert(temp,p);
else
printf("\nThis position is not true.");
}
List Input_List(unsigned int n) {
List temp = MakeNull_List();
ElementType x;
unsigned int i = 1;
while(i<=n) {
printf("\tValue %d = ",i);
scanf("%d",&x);
Insert(temp,Make_Node(x));
i++;
}
return temp;
}
void Out_List(List L) {
List temp = L;
while(!Empty_List(temp)) {
printf("%d\t",temp->Next->Element);
temp = temp->Next;
}
}
THUẬT TOÁN BUBBLE SORT
Code:
//Sort List
void Bubble_Sort(List L) {
for(List i=L->Next; i!=NULL; i=i->Next)
for(List j=i->Next; j!=NULL; j=j->Next)
if(i->Element>j->Element)
{
ElementType temp = i->Element;
i->Element = j->Element;
j->Element = temp;
}
}
CHƯƠNG TRÌNH MẪU
Code:
#include "conio.h"
#include "stdio.h"
#include "alloc.h"
typedef unsigned int Position;
typedef int ElementType;
typedef struct Node{
ElementType Element;
Node* Next;
};
typedef Node * List;
Node * Make_Node(ElementType x) {
Node * temp = (Node*)malloc(sizeof(Node));
temp->Element = x;
return temp;
}
List MakeNull_List() {
List temp = (List)malloc(sizeof(List));
temp->Next = NULL;
return temp;
}
char Empty_List(List L) {
return L->Next == NULL;
}
void Insert(List L, Node * p) {
p->Next = L->Next;
L->Next = p;
}
void Insert(List L, Node * p, Position i) {
List temp = L;
Position j = 1;
while(j<i && temp!=NULL) {
temp = temp->Next;
j++;
}
if(i==j)
Insert(temp,p);
else
printf("\nThis position is not true.");
}
List Input_List(unsigned int n) {
List temp = MakeNull_List();
ElementType x;
unsigned int i = 1;
while(i<=n) {
printf("\tValue %d = ",i);
scanf("%d",&x);
Insert(temp,Make_Node(x));
i++;
}
return temp;
}
void Out_List(List L) {
List temp = L;
while(!Empty_List(temp)) {
printf("%d\t",temp->Next->Element);
temp = temp->Next;
}
}
//Sort List
void Bubble_Sort(List L) {
for(List i=L->Next; i!=NULL; i=i->Next)
for(List j=i->Next; j!=NULL; j=j->Next)
if(i->Element>j->Element)
{
ElementType temp = i->Element;
i->Element = j->Element;
j->Element = temp;
}
}
void main() {
clrscr();
unsigned int n;
Position p;
ElementType x;
printf("Nhap n = ");
scanf("%d",&n);
List S = Input_List(n);
printf("This List: \n");
Out_List(S);
Bubble_Sort(S);
printf("\nThe new List: \n");
Out_List(S);
getch();
}