zoukankan      html  css  js  c++  java
  • 各类排序源代码

    #include<stdio.h>
    #include<stdlib.h>
    #define leftchild(i) (2*(i)+1)
    void insersort(int a[],int n)
    {
    for(int i=1;i<n;i++)
    {
    int temp=a[i];
    for(int j=i-1;j>0&&temp<a[j];j--)
    a[j+1]=a[j];
    a[j+1]=temp;
    }
    }
    void bubblesort(int a[],int n)
    { int temp;
    for(int i=0;i<n;i++)
    {
    for(int j=0;j<=n-i-1;j++)
    if(a[j]>a[j+1])
    {
    temp=a[j];
    a[j]=a[j+1];
    a[j+1]=a[j];
    }

    }

    }

    int partition(int a[],int i,int j)
    {
    int temp=a[i];

    while(i<j)

    {
    while(a[j]>temp && i<j)
    j--;
    if(i<j)
    a[i++]=a[j];
    while(a[i]<temp && i<j)
    i++;
    if(i<j)
    a[j--]=a[i];

    }
    a[i]=temp;
    return i;
    }

    void quicksort(int a[],int i,int j)
    {

    if(i<j)
    {

    int k=partition(a,i,j);
    quicksort(a,i,k-1);
    quicksort(a,k+1,j);
    }

    }
    void quickselectsort(int a[],int n)
    {
    int min;
    int temp;
    for(int i=0;i<n-1;i++)
    {
    min=i;
    for(int j=i+1;j<n;j++)
    {
    if(a[j]<a[i])
    min=j;
    temp=a[min];
    a[min]=a[i];
    a[i]=temp;
    }
    }
    }
    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 = 1; i <= n; i++)
    {
    a[i] = rand() % 100 + 1;
    printf("%d ", a[i]);
    }
    a[i] = '';
    printf(" ");
    insersort(a,n);
    printf(" 插入排序结果为(由小到大):");
    for (i = 1; i <= n; i++)
    printf("%d ", a[i]);

    bubblesort(a,n);
    printf(" 冒泡排序结果为(由小到大):");
    for (i = 1; i <= n; i++)
    printf("%d ", a[i]);

    quicksort(a,0,n-1);
    printf(" 快速排序结果为(由小到大):");
    for (i = 1; i <= n; i++)
    printf("%d ", a[i]);

    quickselectsort(a,n);
    printf(" 快速选择排序结果为(由小到大):");
    for (i = 1; i <= n; i++)
    printf("%d ", a[i]);

    heapsort(a,n);
    printf(" 堆排序结果为(由小到大):");
    for (i = 1; i <= n; i++)
    printf("%d ", a[i]);
    }

  • 相关阅读:
    王健林:在中国远离政府太假了 期望王思聪稳重
    科目二很难考吗?经验全在这里!
    HTTP 的长连接和短连接
    JS中实现字符串和数组的相互转化
    Maven介绍,包括作用、核心概念、用法、常用命令、扩展及配置
    kafka数据可靠性深度解读
    深入浅出JMS(二)--ActiveMQ简单介绍以及安装
    ActiveMQ入门实例
    activemq的几种基本通信方式总结
    mysql按年度、季度、月度、周、日SQL统计查询
  • 原文地址:https://www.cnblogs.com/qin5429/p/8395130.html
Copyright © 2011-2022 走看看