Quicksort算法计数器

时间:2019-01-20 01:42:47

标签: java performance sorting quicksort

我的教授要求我们选择最佳的排序算法,我们选择了Quicksort。给我们的任务是创建一个程序,该程序使用所选算法但仅使用一种方法对整数数组进行排序,并创建一个计数器,该计数器对程序中一行代码运行的次数进行计数,以确定最快和最佳的内存明智的算法。

我知道Quicksort非常适合用于处理大量数据,这就是为什么我的计数器计数很高的原因,但是我只是想检查放置计数器的行是否正确。有什么建议吗?

public class JavaProgram {

    @FunctionalInterface
    public interface Func {
        void call(int[] arr, int i, int j);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int counter=0; counter++;
        System.out.println("Enter size of array: "); counter++;
        int x = sc.nextInt(); counter++;
        System.out.println("Enter numbers in array: "); counter++;
        int[] numbers = new int[x]; counter++;
        for(int i=0;i<numbers.length;i++)
        {
            numbers[i] = sc.nextInt(); counter++;
        }

        Func swap = (int[] arr, int i, int j) -> {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }; counter++;

        Stack<Integer> stack = new Stack<>(); counter++;
        stack.push(0); counter++;
        stack.push(numbers.length); counter++;

        while (!stack.isEmpty()) { counter++;
            int end = stack.pop(); counter++;
            int start = stack.pop(); counter++;
            if (end - start < 2) { counter++;
                continue;
            } counter++;

            // partitioning part
            int position = start + ((end - start) / 2); counter++;
            int low = start; counter++;
            int high = end - 2; counter++;
            int piv = numbers[position]; counter++;
            swap.call(numbers, position, end - 1); counter++;
            while (low < high) { counter++;
                if (numbers[low] < piv) { counter++;
                    low++; counter++;
                } else if (numbers[high] >= piv) { counter++;
                    high--; counter++;
                } else { counter++;
                    swap.call(numbers, low, high); counter++;
                }
            }
            position = high; counter++;
            if (numbers[high] < piv) { counter++;
                position++; counter++;
            }
            swap.call(numbers, end - 1, position); counter++;


            stack.push(position + 1); counter++;
            stack.push(end); counter++;
            stack.push(start); counter++;
            stack.push(position); counter++;
        }

        System.out.println("Sorted array: " + Arrays.toString(numbers)); counter++;
        System.out.println("Counter: "+counter);
    }
}  

0 个答案:

没有答案