简单选择排序和堆排序问题写了一个程序用WIN-TC编译老有错误,希望高手帮忙改下,在线等#include #include #include #define datatype int void SelectSort(datatype R[],int n) { int i,k,j; for(i=1;i
来源:学生作业帮助网 编辑:作业帮 时间:2024/11/16 07:01:14
简单选择排序和堆排序问题写了一个程序用WIN-TC编译老有错误,希望高手帮忙改下,在线等#include #include #include #define datatype int void SelectSort(datatype R[],int n) { int i,k,j; for(i=1;i
简单选择排序和堆排序问题
写了一个程序用WIN-TC编译老有错误,希望高手帮忙改下,在线等
#include
#include
#include
#define datatype int
void SelectSort(datatype R[],int n)
{
int i,k,j;
for(i=1;i
简单选择排序和堆排序问题写了一个程序用WIN-TC编译老有错误,希望高手帮忙改下,在线等#include #include #include #define datatype int void SelectSort(datatype R[],int n) { int i,k,j; for(i=1;i
你那个叫归并排序,我三个都写给你:
#include
#include
void swap(int* a,int* b)
{
int t;
t = *a; *a = *b; *b = t;
}
void show(char* s,int* a,int* b)
{
printf(s);
while(a != b)
printf("%d ",*a++);
putchar('\n');
}
void select_sort(int a[],int n)
{
int i,j,m;
for(i = 0; i < n; ++i) {
m = i;
for(j = i; j < n; ++j)
if(a[m] > a[j])
m = j;
swap(a+i,a+m);
}
}
void merge(int a[],int m,int n)
{
static int s[256];
int i,j,k;
for(i = k = 0,j = m; i < m && j < n;)
if(a[i] > a[j])
s[k++] = a[i++];
else
s[k++] = a[j++];
if(i == m)
i = j,j = n;
else
j = m;
while(i < j)
s[k++] = a[i++];
for(i = 0; i < n; ++i)
a[i] = s[i];
}
void merge_sort(int a[],int n)
{
int m;
if(n < 2)
return;
m = n/2;
merge_sort(a,m);
merge_sort(a+m,n-m);
merge(a,m,n);
}
void heapify(int a[],int i,int n)
{
int l,r,m;
while(1) {
r = (i + 1)*2;
l = r - 1;
m = l < n && a[l] > a[i] l :i;
m = r < n && a[r] > a[m] r :m;
if(m != i)
swap(a+i,a+m),i = m;
else break;
}
}
void heap_sort(int a[],int n)
{
int i;
for(i = (n-1)/2; i >= 0; --i)
heapify(a,i,n);
for(i = n-1; i > 0; --i) {
swap(a,a+i);
heapify(a,0,--n);
}
}
int main()
{
int a[] = {6,1,3,8,4,0,9,7,5,2};
select_sort(a,10);
show("选择排序:\t",a,a+10);
merge_sort(a,10);
show("归并排序:\t",a,a+10);
heap_sort(a,10);
show("堆排序:\t\t",a,a+10);
return 0;
}