数据机构快速排序之c语言实现

#if 01
//selectSort && quickSort comparison
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void swap(int *a, int *b)
{
        int temp = *a;
        *a = *b;
        *b = temp;
}

int partition(int a[], int idxLeft, int idxRight, int idxPivot)
{
        int i, idxCur = idxLeft;

        int pivot = a[idxPivot];
        swap(&a[idxPivot], &a[idxRight]);

        for(i = idxLeft; i < idxRight; i++){
                if(a[i] <= pivot){
                        swap(&a[i], &a[idxCur]);
                        idxCur++;
                }
        }

        swap(&a[idxCur], &a[idxRight]);
        return idxCur;
}

void quicksort(int a[], int idxLeft, int idxRight)
{
        if(idxLeft >= idxRight){
                return;
        }

        int idxPivot;
        idxPivot = partition(a, idxLeft, idxRight, (idxRight + idxLeft)/2);

        quicksort(a, idxLeft, idxPivot - 1);
        quicksort(a, idxPivot + 1, idxRight);
}

void selectSort(int a[], int size)
{
        int i, j, aux;//auxiliary
        for(i = 0; i< size - 1; i++){
                aux = i;
                for(j = i + 1; j < size; j++){
                        if(a[aux] > a[j]){
                                aux = j;
                        }
                }
                if(i != aux){
                        swap(&a[i], &a[aux]);
                }
        }
}

#define DEBUG_SORTx
int main(int argc, char **argv)
{
        if(argc != 2){
                printf("\tusage : ./test SIZE\n");
                return -1;
        }
        //the larger the SIZE, the better of the quick sort
        int SIZE = atoi(argv[1]);
        int a[SIZE], i, b[SIZE];
        struct timeval tv1, tv2, tv3;

        srand(time(NULL)^getpid());

        for(i = 0; i < SIZE; i++){
                a[i] = rand() % 100;
        }
        a[0] = 73, a[1] = 97, a[2]= 26;
        memcpy(b, a, sizeof(a));

        int size = sizeof(a)/sizeof(int);

        gettimeofday(&tv1, NULL);       //(2)

        selectSort(a, size);

        gettimeofday(&tv2, NULL);

        printf("s : %.3lf ms\n", (tv2.tv_usec - tv1.tv_usec) * 1.0 / 1000 + (tv2.tv_sec - tv1.tv_sec) * 1000);

        quicksort(b, 0, size - 1);
        gettimeofday(&tv3, NULL);

        printf("q : %.3lf ms\n", (tv3.tv_usec - tv2.tv_usec) * 1.0 / 1000 + (tv3.tv_sec - tv2.tv_sec) * 1000);

#ifdef DEBUG_SORT
        for(i = 0; i< size; i++){
                printf("%d\t", a[i]);
        }
        printf("\n");

        for(i = 0; i< size; i++){
                printf("%d\t", b[i]);
        }
        printf("\n");
#endif

        return 0;
}
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值