快速排序学习(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);
}
}