想想为什么这两段代码,一段可以实现快排,一段实现不了?

发布时间 2023-12-09 15:42:32作者: Azzero

可实现代码

#include <stdio.h>
void quicksort(int a[],int i,int j);

int main(){
    int num;
    int a[10001]={0};
    scanf("%d\n",&num);
    int i=0;
    
    while(i < num){
        scanf("%d",&a[i]);
        i++;
    }
    quicksort(a,0,num-1);
    i=0;
    while(i < num){
        printf("%d ",a[i]);
        i++;
    }
    return 0;
}

void quicksort(int a[],int i,int j){
    int low=i,high=j;
    int key=a[i];
    int temp;
    if(low >= high){
        return;
    }
    while(low < high){
        while(low<high && a[high]>=key){
            high--;
        }
        if(a[high] < key){
            temp=a[high];
            a[high]=a[low];
            a[low]=temp;
        }
        while(low<high && a[low]<=key){
            low++;
        }
        if(a[low] > key){
            temp=a[low];
            a[low]=a[high];
            a[high]=temp;
        }
    }
    quicksort(a,i,low-1);
    quicksort(a,low+1,j);    
}

不能实现

void quicksort(int a[],int i,int j){
    int key,temp;
    int b=i,c=j;
    if(i >= j){
        printf("eee\n");
        printf("%d %d\n",b,c);
        return;
    }
    printf("%d %d\n",i,j);
    while(i < j){
        key=a[i];
        while(i < j && a[j] >= key){
            j--;
        }
        if(a[j] < key){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
        }
        while(i < j && a[i] <= key){
            i++;
        }
        if(a[i] > key){
            temp=a[j];
            a[j]=a[i];
            a[i]=temp;
        }
    }
    quicksort(a,b,i);
    quicksort(a,i+1,c);

}