首页 文章

快速排序算法无法正常工作?

提问于
浏览
0

我的快速排序算法没有返回正确的输出 . 我的输出只是右侧的枢轴元素,左侧的元素小于枢轴元素,右侧的元素大于枢轴元素 .

enter image description here

import java.util.Timer;

class QuickSort {

    public static void quicksort(int[] array, int left, int right) {

        if (left < right) {
            int q = partition(array, left, right);
            quicksort(array, left, q - 1);
            quicksort(array, q + 1, right);
        }
    }

    public static int partition(int[] array, int start, int end) {
        int x = array[end];
        int i = start - 1;
        int temp = 0;
        for (int j = start; j < end - 1; j++) {
            if (array[j] <= x) {
                i++;
                temp = array[j];
                array[j] = array[i];
                array[i] = temp;
            }
        }

        temp = array[end];
        array[end] = array[i + 1];
        array[i + 1] = temp;
        return i + 1;
    }

    public static void main(String[] args) {
        int[] array = { 2, 8, 7, 1, 3, 5, 6, 4 };

        long totalTime = 0;

        System.out.println("Unsorted array");
        for (int i = 0; i < array.length; i++)
            System.out.print(array[i] + " ");
        System.out.println();

        long startTime = System.currentTimeMillis();

        quicksort(array, 0, array.length - 1);

        long endTime = System.currentTimeMillis();
        totalTime = endTime - startTime;

        System.out.println("Total time taken by the algorithm " + totalTime);

        System.out.println("Sorted array");
        for (int i = 0; i < array.length; i++)
            System.out.print(array[i] + " ");
    }
}

请告诉我我的错误并更正我的代码 . 谢谢 .

1 回答

  • 0

    谢谢你看看这个问题 . 在这里,是纠正 .

    for(int j = start; j <= end-1; j++){
            if(array[j] <= x){
                i++;
                temp = array[j];
                array[j] = array[i];
                array[i] = temp;
            }
    
        }
    

    for循环也将在end-1上运行 .

相关问题