0

我没有从任何地方看到这个算法,而是自己做的,只是看到了快速排序是如何工作的,这是在 Java 中,问题是,它排序很好,对最多 6 个值的数量有好处,它挂在值上的时间超过6. 或者可能有其他一些我不知道的问题。这是代码-

import java.util.Scanner;

class Main {
public static void main(String[] args) {

        System.out.print("Enter number of elements= ");

        int x, a[];
        Scanner z = new Scanner(System.in);
        x = Integer.parseInt(z.next());
        a = new int[x];

        for(int i = 0; i < x; i++){
            System.out.print("Enter element #"+(i+1)+"= ");
            a[i] = Integer.parseInt(z.next());
        }

        QuickSort(a, 0, x-1);

        System.out.print("A= ");
        for(int i = 0; i < x; i++){
            System.out.print(a[i]+" ");
        }
    }

    public static void QuickSort(int a[], int low, int high){
        if(low >= high)
            return;

        int l = low + 1, h = high, flag = 0, temp;

        while(l <= h){
            if(a[low] >= a[l]){
                ++l;
                ++flag;
            }
            if(a[low] <a [h]){
                --h;
                ++flag;
            } else if(flag == 0){
                temp = a[l];
                a[l] = a[h];
                a[h] = temp;
                ++l;
                --h;
            }
        }

        temp = a[low];
        a[low] = a[h];
        a[h] = temp;
        QuickSort(a, low, h-1);
        QuickSort(a, h+1, high);
    }
}

感谢所有的帮助。

4

1 回答 1

0

问题是您忘记flag在内部循环中设置回 0,从而导致它进入无限循环。

flag=0;在之后添加该while(l<=h){行使其工作。尽管您应该真正学习编写并非完全难以辨认的代码。这不仅会让人们更容易地帮助你,它甚至会让你更容易发现这样的错误。

Also, you should really learn basic troubleshooting skills before asking for help. I didn't even need to use a debugger, I just added a couple of print statements to see where it was getting stuck.

于 2013-03-11T14:57:00.210 回答