Given an integer array, find the top_k_largest numbers in it.
Quick sort then create a new array to store them.
public int[] topk(int[] nums, int k) {
quickSort(nums,0,nums.length-1);
int[] topk=new int[k];
for(int i=0;i<k && i<nums.length;i++){
topk[i]=nums[i];
}
return topk;
}
//descending the quick sort
public static int partition(int[] arr,int left,int right)
{
int i=left;
int j=right;
int temp;
int pivot= arr[(left+right)/2];
while(i<=j)
{
while(arr[i]>pivot)
i++;
while(arr[j]<pivot)
j--;
if(i<=j)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
return i;
}
//descending
public static void quickSort(int[] arr,int left,int right)
{
int index=partition(arr,left,right);
if(left<index-1)
{
quickSort(arr,left,index-1);
}
if(right>index)
{
quickSort(arr,index,right);
}
}