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

来源:互联网 发布:男士服装搭配软件 编辑:程序博客网 时间:2024/05/29 04:38
#if 01
//selectSort && quickSortcomparison
#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, intidxPivot)
{
       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 : ./testSIZE\n");
              return -1;
       }
       //the larger the SIZE, the better of the quicksort
       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
原创粉丝点击