C 快速排序是否返回未排序的中间/中间元素?
我对编程相当陌生,并且已经学习排序算法一段时间了。我在下面用C实现了快速排序。它使用三个分区的中间值来选择枢轴。 代码的问题是,每次我运行它时,应该是排序数组的中值/中值的元素都是未排序的,即它发生在其他地方。 代码如下:C 快速排序是否返回未排序的中间/中间元素?,c,algorithm,sorting,C,Algorithm,Sorting,我对编程相当陌生,并且已经学习排序算法一段时间了。我在下面用C实现了快速排序。它使用三个分区的中间值来选择枢轴。 代码的问题是,每次我运行它时,应该是排序数组的中值/中值的元素都是未排序的,即它发生在其他地方。 代码如下: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> void swap(int *x, int *y) { in
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
return ;
}
int median3(int a[], int left, int right)//Uses median of three partitioning technique
{
int center = (left + right)/2;
if (a[center] < a[left])
swap(&a[left],&a[center]);
if (a[right] < a[left])
swap(&a[left],&a[right]);
if (a[right]< a[center])
swap(&a[center],&a[right]);
swap(&a[center], &a[right - 1]);//since the largest is already in the right.
return a[right - 1];
}
void quicksort(int a[], int left, int right)
{
if (left < right) {
int pivot = median3(a,left,right);
int i = left;
int j = right - 1;
for ( ; ;) {
while(a[++i]<pivot) {}
while(pivot<a[--j]) {}
if ( i < j)
swap(&a[i],&a[j]);
else
break ;
}
swap(&a[i],& a[right -1]);
quicksort(a,left,i-1);
quicksort(a,i+1,right);
}
return ;
}
int main(int argc, char* argv[])
{
int i;
int a[] = {8,1,4,9,6,3,5,2,7,0};
quicksort(a,0,9);
for ( i = 0 ; i < 10 ; i++)
printf("%d\n",a[i]);
return 0;
}
#包括
#包括
#包括
#包括
无效交换(int*x,int*y)
{
int temp=*x;
*x=*y;
*y=温度;
返回;
}
int median3(int a[],int left,int right)//使用三个分区的中间值技术
{
int center=(左+右)/2;
if(a[中间]而(a[++i]注意边缘情况,其中left==right-1
:
void quicksort(int a[], int left, int right)
{
if (left < right) {
int pivot = median3(a,left,right);
if (left == right - 1) return; // only two elements, already sorted by median3()
int i = left;
int j = right - 1;
void快速排序(int a[],int left,int right)
{
if(左<右){
int pivot=median3(a,左,右);
if(left==right-1)return;//只有两个元素,已经按median3()排序
int i=左;
int j=右-1;
您是否尝试在调试器中单步执行代码以查看实际情况?您的实现是错误的,不仅是“重新运行未排序的中间/中间元素”,更改测试数据,您将看到输出混乱。我建议您重新学习算法并重新编写代码。尤其是,(非常感谢您的帮助。:)