Please check why my 2nd Test Case failed.
One of the testcases failed
I don’t know how to get code link. You can check my submissions.
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int[]arr=new int [n];
for(int i =0;i<n;i++){
arr[i]=sc.nextInt();
}
quickSort(arr,0,arr.length-1);
for(int val : arr){
System.out.print(val+" ");
}
}
public static void quickSort(int[]arr,int lo,int hi){
if(lo>=hi){
return;
}
int left=0;
int right=arr.length-1;
int mid=(lo+hi)/2;
int pivot=arr[mid];
while(left<=right){
while(arr[left]<pivot){
left++;
}
while(arr[right]>pivot){
right–;
}
if(left<=right){
int temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right–;
}
}
quickSort(arr,lo,right);
quickSort(arr,left,hi);
}
}
One thing I just realized is that question is saying to use randomized quicksort. Can you explain this? as in lectures they have only taught quicksort.
@Syed-Siddiqui-2497215583854102
public static void quickSort(int[]arr,int lo,int hi){
if(lo>=hi){
return;
}
int left=lo;
int right=hi;
int mid=(lo+hi)/2;
int pivot=arr[mid];
while(left<=right){
while(arr[left]<pivot){
left++;
}
while(arr[right]>pivot){
right–;
}
if(left<=right){
int temp=arr[left];
arr[left]=arr[right];
arr[right]=temp;
left++;
right–;
}
}
quickSort(arr,lo,right);
quickSort(arr,left,hi);
}
i have corrected your code
you need to take
left=lo;
right=hi;
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
