哈哈, 新手的快速排序
#include <stdio.h>void quick_sort_b_s(int [], int, int);//从大到小
void quick_sort_s_b(int [], int, int);//从小到大
void quick_sort_b_s(int array[], int left, int right)
{
int a = left, b = right, c;
int p_point = array[(a + b) / 2];//设置基准点
while (a <= b)
{
//找到小于基准点的数
while (array > p_point)
{
a++;
}
//找到大于基准点的数
while (array < p_point)
{
b--;
}
//将两者互换
if (a <= b)
{
c = array;
array = array;
array = c;
a++;
b--;
}
}
//分成两组排序
if (left < b)//
{
quick_sort_b_s(array, left, b);//因为将两者互换了位置, 所以array, array互换了位置, array较大
}
if (a < right)
{
quick_sort_b_s(array, a, right);
}
}
void quick_sort_s_b(int array[], int left, int right)
{
int a = left, b = right, c;
int p_point = array[(a + b) / 2];//设置基准点!
while (a <= b)
{
//从左往右找大于等于基准点的数
while (array < p_point)
{
a++;
}
//从右向左找小于等于基准点得数
while (array > p_point)
{
b--;
}
//将两数互换
if (a <= b)//必须设置, 从而将大数往后排!
{
c = array;
array = array;
array = c;
//要达成语句结束条件!
a++;
b--;
}
}
//分成两部分递归!
if (left < b)
{
quick_sort_s_b(array, left, b);
}
if (right > a)
{
quick_sort_s_b(array, a, right);
}
}
int main(void)
{
int array[] = {1, 9, 7, 76, 8, 87, 58, 5, 59, 45, 0, 87, 57, -199};//定义数组
int length = sizeof(array) / sizeof(array);//计算有几个数字
int left = 0, right = length - 1;
quick_sort_s_b(array, left, right);
int i;
for (i = 0; i < length; i++)
{
printf("%d ", array);
}
printf("\n");
quick_sort_b_s(array, left, right);
for (i = 0; i < length; i++)
{
printf("%d ", array);
}
return 0;
} #include <stdio.h>
void quick_sort_s_b(int [], int, int);
void quick_sort_b_s(int [], int, int);
void quick_sort_s_b(int array[], int left, int right)
{
int a = left, b = right, c;
int p_point = array[(a + b) / 2];//设置基准点!
while (a <= b)
{
//从左往右找大于等于基准点的数
while (array < p_point)
{
a++;
}
//从右向左找小于等于基准点得数
while (array > p_point)
{
b--;
}
//将两数互换
if (a <= b)//必须设置, 从而将大数往后排!
{
c = array;
array = array;
array = c;
//要达成语句结束条件!
a++;
b--;
}
}
//分成两部分递归!
if (left < b)
{
quick_sort_s_b(array, left, b);
}
if (right > a)
{
quick_sort_s_b(array, a, right);
}
}
void quick_sort_b_s(int array[], int left, int right)
{
int a = left, b = right, c;
int p_point = array[(a + b) / 2];//设置基准点!
while (a <= b)
{
//从左往右找小于等于基准点的数
while (array > p_point)
{
a++;
}
//从右向左找大于等于基准点得数
while (array < p_point)
{
b--;
}
//将两数互换
if (a <= b)//必须设置, 从而将大数往后排!
{
c = array;
array = array;
array = c;
//要达成语句结束条件!
a++;
b--;
}
}
//分成两部分递归!
if (left < b)
{
quick_sort_b_s(array, left, b);
}
if (right > a)
{
quick_sort_b_s(array, a, right);
}
}
int main()
{
int length, num;
printf("请输入要排序几个数字:");
scanf("%d", &length);
int array1;
for (num = 0; num < length; num++)
{
printf("请输入第%d个数字:", num + 1);
scanf("%d", &array1);
}
int array2;
for (num = 0; num < length; num++)
{
array2 = array1;
}
int i;
printf("从小到大为:");
quick_sort_s_b(array1, 0, length - 1);
for (i = 0; i < length; i++)
{
printf("%d, ", array1);
}
putchar('\n');
printf("从大到小为:");
quick_sort_b_s(array2, 0, length -1);
for (i = 0; i < length; i++)
{
printf("%d, ", array2);
}
return 0;
} 嗯嗯, 修改了一下, 代码有些繁琐, 请高手指教
页:
[1]