示例代码1:
//快速排序
void fun(int a[], int L, int R)
{
if (L >= R)
return;
int left = L;
int right = R;
int temp = a[L];
while (left < right)
{
while (left < right && a[right] >= temp)
right--;
if (left < right)
a[left] = a[right];
while (left < right && a[left] <= temp)
left++;
if (left < right)
a[right] = a[left];
if (left >= right)
a[left] = temp;
}
fun(a, L, left);
fun(a, left + 1, R);
}
示例代码2:
//快速排序
int quick_sort(int *arr, int low, int high)
{
int l=low,h=high;
if (arr == NULL)
{
printf("数组为空\n");
return -1;
}
if (low >= high) //递归退出条件
{
return 0;
}
int temp = arr[low]; //保存一下基准值
while (low < high)
{
while (low < high && temp <= arr[high])
{ //high--比较
high--;
}
arr[low] = arr[high];
while (low < high && temp >= arr[low])
{ //low++比较
low++;
}
arr[high] = arr[low];
}
arr[low] = temp; //把基准值放到中轴上
quick_sort(arr, l, low- 1); //中轴左半区
quick_sort(arr, low + 1, h); //中轴右半区
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/************************ 快速排序 ************************/
#define N 10
//快速排序
void quick_sort(int *arr, int low, int high)
{
int l = low, h = high;
if (low >= high) //递归退出条件
return;
int temp = arr[low]; //保存一下基准值
while (low < high)
{
while (low < high && temp <= arr[high])
high--;
arr[low] = arr[high];
while (low < high && temp >= arr[low])
low++;
arr[high] = arr[low];
}
arr[low] = temp; //把基准值放到中轴上
quick_sort(arr, l, low - 1); //中轴左半区
quick_sort(arr, low + 1, h); //中轴右半区
}
int main()
{
int arr[N] = {0}, i, t; // 修改初始化为0,避免未定义的行为
srand(time(NULL)); //在这里初始化随机数种子,只需调用一次即可
for (i = 0; i < N; i++)
{
arr[i] = rand() % 100 + 1; // 在这里添加类型说明符,以明确这是整数赋值操作
}
printf("快排之前的:");
for (i = 0; i < N; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
quick_sort(arr, 0, N - 1);
printf("快排之后的:");
for (i = 0; i < N; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}