Running Time of Quicksort

  • + 0 comments
    import java.util.Scanner;
    
    public class CompareSorts {
    
        private static int quickSortSwaps = 0;
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            int[] arrQuickSort = new int[n];
            int[] arrInsertionSort = new int[n];
    
            for (int i = 0; i < n; i++) {
                int num = scanner.nextInt();
                arrQuickSort[i] = num;
                arrInsertionSort[i] = num;
            }
    
            int insertionSortShifts = insertionSort(arrInsertionSort);
            quickSort(arrQuickSort, 0, n - 1);
    
            int result = insertionSortShifts - quickSortSwaps;
            System.out.println(result);
    
            scanner.close();
        }
    
        public static void quickSort(int[] arr, int low, int high) {
            if (low < high) {
                int pivotIndex = partition(arr, low, high);
                quickSort(arr, low, pivotIndex - 1);
                quickSort(arr, pivotIndex + 1, high);
            }
        }
    
        public static int partition(int[] arr, int low, int high) {
            int pivot = arr[high];
            int i = low - 1;
    
            for (int j = low; j < high; j++) {
                if (arr[j] < pivot) {
                    i++;
                    swap(arr, i, j);
                }
            }
    
            swap(arr, i + 1, high);
            return i + 1;
        }
    
        public static void swap(int[] arr, int i, int j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            quickSortSwaps++; // Increment the swap count
        }
    
        public static int insertionSort(int[] arr) {
            int shifts = 0;
    
            for (int i = 1; i < arr.length; i++) {
                int key = arr[i];
                int j = i - 1;
    
                while (j >= 0 && arr[j] > key) {
                    arr[j + 1] = arr[j];
                    j--;
                    shifts++;
                }
    
                arr[j + 1] = key;
            }
    
            return shifts;
        }
    }