随手写了几个排序

花了差不多一个小时,堆排还有点不好使,有待改正;

#include <iostream>
#include <stdlib.h>
#include <time.h>
const int maxn = 20;
using namespace std;
int A[maxn];

void insertSort() //直接插入排序;
{
    int tmp,i,j;
    for (i = 1;i < maxn; i++ )
    {
        tmp = A[i];
        for (j = i-1 ; j >= 0 && A[j] > tmp; j--)
        {
            if (A[j] > tmp) A[j+1] = A[j];
        }
        A[j+1]=tmp;
    }
}

void shellSort()    //希尔排序;
{
    int tmp,i,j;
    for (int d = maxn/2 ; d >= 1 ; d/=2)
    {
        for (i = d+1;i < maxn; i++)
        {
            tmp = A[i];
            for (j = i-d ; j >= 0 && A[j] > tmp;j-=d)
            {
                A[j+d]=A[j];
            }
            A[j+d] = tmp;
        }
    }
}

void bubbleSort()   //冒泡排序;
{
    int bound , exchange = maxn-1 , i;
    while (exchange)
    {
        bound = exchange;
        exchange = 0;
        for (i = 0 ; i < bound; i++)
        {
            if (A[i] > A[i+1])
            {
                swap(A[i],A[i+1]);
                exchange = i;
            }
        }
    }
}

void selectSort()
{
    int i,j,index;
    for (i = 0 ; i < maxn ; i++)
    {
        index = i;
        for (j = i+1;j< maxn ; j++)
        {
            if (A[j] < A[index]) index = j;
        }
        if (i != index ) swap(A[i],A[index]);
    }
}

int partition(int first,int end)
{
    int i = first;
    int j = end;
    while (i < j)
    {
        while (i < j && A[i]<=A[j]) i++;
        if (i < j )
        {
            swap(A[i],A[j]);
            j--;
        }
        while (i < j && A[i]<=A[j])j--;
        if (i<j)
        {
            swap(A[i],A[j]);
            i++;
        }

    }
    return i;
}

void quickSort(int first,int end)  //排序;
{
    if (first < end)
    {
        int pivot = partition(first,end);
        quickSort(first,pivot-1);
        quickSort(pivot+1,end);
    }
}

void sift(int k)
{
    int i = k;
    int j = 2*k;
    while (j < maxn)
    {
        if (j<maxn && A[j]<A[j+1]) j++;
        if (A[i] > A[j]) break;
        else
        {
            swap(A[i],A[j]);
            i = j;
            j = 2*i;
        }
    }
}

void heapSort()
{
    for (int  i = maxn/2 ; i >= 0 ; i--)
        sift(i);
    for (int i = 0;i < maxn;i++)
    {
        swap(A[0],A[maxn-i-1]);
        sift(0);
    }
}

int main()
{
    srand((unsigned)time( NULL ));  //srand()函数产生一个以当前时间开始的随机种子.应该放在for等循环语句前面 不然要很长时间等待
    for (int i = 0 ; i < maxn; i++)
    {
        A[i] =  rand()%100;
        cout<<A[i]<<" ";
    }
    cout<<endl;

    //insertSort();
    //shellSort();
    //bubbleSort();
    //selectSort();
    //quickSort(0,maxn-1);
    heapSort();

    for (int i = 0 ; i < maxn; i++)
        cout<<A[i]<<" ";
    cout<<endl;
    return 0;
}

 

posted on 2012-05-16 21:20  _Clarence  阅读(50)  评论(0编辑  收藏

导航

统计