Các thuật toán sắp xếp
Sắp xếp chọn:
void selection_sort(){
int i, j, k, temp;
for (i = 0; i< N; i++){
k = i;
for (j = i+1; j < N; j++){
if (a[j] < a[k]) k = j;
}
temp = a[i]; a[i] =a [k]; a[k] = temp;
}
}
Insert sort:
void insertion_sort(){
int i, j, k, temp;
for (i = 1; i< N; i++){
temp = a[i];
j=i-1;
while ((a[j] > temp)&&(j>=0)) {
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
Sắp xếp nổi bọt:
void bubble_sort(){
int i, j, temp, no_exchange;
i = 1;
do{
no_exchange = 1;
for (j=n-1; j >= i; j--){
if (a[j-1] > a[j]){
temp=a[j-1];
a[j-1]=a[j];
a[j]=temp;
no_exchange = 0;
}
}
Sắp xếp Quick:
void quick(int left, int right) {
int i,j;
int x,y;
i=left; j=right;
x= a[left];
do {
while(a[i]<x && i<right) i++;
while(a[j]>x && j>left) j--;
if(i<=j){
y=a[i];a[i]=a[j];a[j]=y;
i++;j--;
}
}while (i<=j);
if (left<j) quick(left,j);
if (i<right) quick(i,right);
}
void quick_sort()
{
quick(0, n-1);
}
Sắp xếp trộn:
void merge_sort(int *a, int left, int right){
int middle;
if (right<=left) return;
middle=(right+left)/2;
merge_sort(a, left, middle);
merge_sort(a, middle+1, right);
merge(a, left, middle ,right);
}
Heap sort
void upheap(int m){
int x;
x=a[m];
while ((a[(m-1)/2]<=x) && (m>0)){
a[m]=a[(m-1)/2];
m=(m-1)/2;
}
a[m]=x;
}
void insert_heap(int x){
a[m]=x;
upheap(m);
m++;
}
void downheap(int k){
int j, x;
x=a[k];
while (k<=(m-2)/2){
j=2*k+1;
if (j<m-1) if (a[j]<a[j+1]) j++;
if (x>=a[j]) break;
a[k]=a[j]; k=j;
}
a[k]=x;
}
int remove_node(){
int temp;
temp=a[0];
a[0]=a[m];
m--;
downheap(0);
return temp;
}
void heap_sort(){
int i;
m=0;
for (i=0; i<=n-1; i++) insert_heap(a[i]);
m=n-1;
for (i=n-1; i>=0; i--) a[i]=remove_node();
}
Bạn đang đọc truyện trên: AzTruyen.Top