快速排序学习(C语言)

快速排序学习(C语言)

注: 我是在Linux下写的代码,有些Linux头文件没删,但这次代码没用到。

新手一名,快速排序研究了很久,见谅。
下面代码包含main函数和一些辅助函数,快速排序在唯一函数中。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include <time.h>

#define My_Rand(a, b) ((rand()) % ((b) - (a) + 1)) + (a)

void my_swap(int *a, int *b);
void show_array(int *array, unsigned size);
int quickSort(int *array, int Left, int Right);
void randNumberFactory(int *array, unsigned size);


int main(void)
{
    unsigned size = 10;
    int array[size];
    //int array[10] = {16, 19, 15, 21, 24, 32, 39, 19, 29, 26};
    randNumberFactory(array, size);

    show_array(array, size);
    quickSort(array, 0, (int)size - 1);//调用快速排序
    show_array(array, size);

    return 0;
}

//--------------------------------------------------
//这是我写的快速排序,其它都为辅助和main
/*
 * Sort the numbers of array by using the quick sort's method
 *The arguments Left and Right is the first and the lastest index of array 
 */
int quickSort(int *array, int Left, int Right)
{
    
    if(array == NULL || Left > Right)
    {
        return 0;
    }

    int p = array[Left];
    int L = Left;
    int R = Right;

    while(L < R)
    {
        while(array[R] > p && L < R)
        {
            R--;
        }

        while(array[L] <= p && L < R)
        {
            L++;
        }

        my_swap(&array[R], &array[L]);

    }

    my_swap(&array[Left], &array[L]);

    quickSort(array, Left, L - 1);
    quickSort(array, R + 1, Right);

    return 0;
}
//--------------------------------------------------

/*Exchange the memery values of both points a and b*/
void my_swap(int *a, int *b)
{
    if(a == b)
    {
        return;
    }
    else if(a == NULL || b == NULL)
    {
        return;
    }

    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}

/*Print all the numbers of array on console*/
void show_array(int *array, unsigned size)
{
    unsigned i;
    for(i = 0; i < size; i++)
    {
        printf("%d(%d) ", array[i], i);
    }
    puts("");
}

/*Full the array with random numbers*/
void randNumberFactory(int *array, unsigned size)
{
    srand((unsigned)time(NULL));
    unsigned i;

    for(i = 0; i < size; i++)
    {
        array[i] = My_Rand(1, 50);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值