Program C : Heapsort
Pada postingan sebelumnya sudah dibahas mengenai algoritma heapsort, jadi kali ini saya akan memberikan source code program heapsort untuk program C.
#include <stdio.h>
int main(){
int l,i,j,k,n,tmp,arr[20];
printf("Masukan Banyaknya bilangan : ");
scanf("%d",&n);
for(i=1;i<=20;i++) arr[i]=0;
for (i=1;i<=n;i++){
printf("masukan bilangan ke-%d : ",i);
scanf("%d",&arr[i]);
}
for (i=1;i<=n;i++){
for(k=1;k<=n;k++){
if(k==1) l=1;
else l=l*2;
if(l==i){
printf("\n");
for(j=1;j<=n-i;j++) printf(" ");
}
}
printf("%d ",arr[i]);
}
printf("\n");
for (i=1;i<=n;i++){
for(k=1;k<=n;k++){
if(k==1) l=1;
else l=l*2;
if(l==i){
printf("\n");
for(j=1;j<=n-i;j++) printf(" ");
}
}
if(arr[i*2]==0||arr[i*2+1]==0){
}
else {
if(arr[i*2]<arr[i]){
tmp=arr[i*2];
arr[i*2]=arr[i];
arr[i]=tmp;
}
if(arr[i*2+1]<arr[i]){
tmp=arr[i*2+1];
arr[i*2+1]=arr[i];
arr[i]=tmp;
}
}
printf("%d ",arr[i]);
}
}
Sekian, Semoga Bermanfaat.
#include <stdio.h>
int main(){
int l,i,j,k,n,tmp,arr[20];
printf("Masukan Banyaknya bilangan : ");
scanf("%d",&n);
for(i=1;i<=20;i++) arr[i]=0;
for (i=1;i<=n;i++){
printf("masukan bilangan ke-%d : ",i);
scanf("%d",&arr[i]);
}
for (i=1;i<=n;i++){
for(k=1;k<=n;k++){
if(k==1) l=1;
else l=l*2;
if(l==i){
printf("\n");
for(j=1;j<=n-i;j++) printf(" ");
}
}
printf("%d ",arr[i]);
}
printf("\n");
for (i=1;i<=n;i++){
for(k=1;k<=n;k++){
if(k==1) l=1;
else l=l*2;
if(l==i){
printf("\n");
for(j=1;j<=n-i;j++) printf(" ");
}
}
if(arr[i*2]==0||arr[i*2+1]==0){
}
else {
if(arr[i*2]<arr[i]){
tmp=arr[i*2];
arr[i*2]=arr[i];
arr[i]=tmp;
}
if(arr[i*2+1]<arr[i]){
tmp=arr[i*2+1];
arr[i*2+1]=arr[i];
arr[i]=tmp;
}
}
printf("%d ",arr[i]);
}
}
Sekian, Semoga Bermanfaat.
0 komentar: