We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.util.Scanner;publicclassCompareSorts{privatestaticintquickSortSwaps=0;publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);intn=scanner.nextInt();int[]arrQuickSort=newint[n];int[]arrInsertionSort=newint[n];for(inti=0;i<n;i++){intnum=scanner.nextInt();arrQuickSort[i]=num;arrInsertionSort[i]=num;}intinsertionSortShifts=insertionSort(arrInsertionSort);quickSort(arrQuickSort,0,n-1);intresult=insertionSortShifts-quickSortSwaps;System.out.println(result);scanner.close();}publicstaticvoidquickSort(int[]arr,intlow,inthigh){if(low<high){intpivotIndex=partition(arr,low,high);quickSort(arr,low,pivotIndex-1);quickSort(arr,pivotIndex+1,high);}}publicstaticintpartition(int[]arr,intlow,inthigh){intpivot=arr[high];inti=low-1;for(intj=low;j<high;j++){if(arr[j]<pivot){i++;swap(arr,i,j);}}swap(arr,i+1,high);returni+1;}publicstaticvoidswap(int[]arr,inti,intj){inttemp=arr[i];arr[i]=arr[j];arr[j]=temp;quickSortSwaps++;// Increment the swap count}publicstaticintinsertionSort(int[]arr){intshifts=0;for(inti=1;i<arr.length;i++){intkey=arr[i];intj=i-1;while(j>=0&&arr[j]>key){arr[j+1]=arr[j];j--;shifts++;}arr[j+1]=key;}returnshifts;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Running Time of Quicksort
You are viewing a single comment's thread. Return to all comments →