zoukankan      html  css  js  c++  java
  • 堆排序

    #include<stdio.h>
    #include<stdlib.h>
    # define LeftChild(i) (2*(i)+1)
    void BuildDown(int a[],int n,int rootIndex)
    {
    int root=a[rootIndex];
    int childIndex=LeftChild(rootIndex);
    while(childIndex<n)
    {
    if(childIndex!=n-1&&a[childIndex+1]>a[childIndex])
    childIndex++;
    if(root<a[childIndex])
    {
    a[rootIndex]=a[childIndex];
    rootIndex=childIndex;
    childIndex=LeftChild(rootIndex);
    }
    else
    break;
    }
    a[rootIndex]=root;
    }
    void HeapSort(int a[],int n)
    {
    int temp;
    for(int rootIndex=(n-2)/2;rootIndex>=0;rootIndex--)
    BuildDown(a,n,rootIndex);
    for(int i=n-1;i>=0;i--)
    {
    temp=a[0];
    a[0]=a[i];
    a[i]=temp;
    BuildDown(a,i,0);
    }
    }
    int main()
    {
    int i, n, a[100];
    printf("请输入需要排序元素的个数:");
    scanf("%d", &n);
    printf("随机生成的数组为:");
    for (i = 0; i < n; i++)
    {
    a[i] = rand() % 100 + 1;
    printf("%d ", a[i]);
    }
    a[i] = '';
    printf(" ");
    HeapSort(a,n);
    printf(" 堆排序结果为(由小到大):");
    for (i = 0; i < n; i++)
    printf("%d ", a[i]);
    }

  • 相关阅读:
    !function() {}()
    element.dataset API
    正则匹配 数字和英文状态下的逗号
    《vim实用技巧》读书笔记
    ajax分页
    smarty分页类
    数组排序
    数组大类
    自动刷新价格
    简单购物车
  • 原文地址:https://www.cnblogs.com/qin5429/p/8392125.html
Copyright © 2011-2022 走看看