Find the n-th largest int in an array

View previous topic View next topic Go down

Find the n-th largest int in an array

Post  skyboard on Mon Oct 03, 2011 5:29 pm

Find the second largest using extra variables:


public class SecondLargest {
public int second(int[] arr){
int max=arr[0];
int second=arr[1];
if(second>max)
{
int temp=second;
second=max;
max=temp;
}
for(int i=0;i<arr.length;i++){
if(arr[i]>max){
second=max;
max=arr[i];
}
if(max>arr[i]&&arr[i]>second){
second=arr[i];
}
}
return second;
}

public static void main(String[] args){
SecondLargest s=new SecondLargest();
int[] arr={1,2,3,4,5,6,5};
System.out.println(s.second(arr));
}
}



Using QuickSearch to find the nth largest element:

public class nthLargest {
private int[] numbers;
private int number;
public int nth(int[] arr, int n){
int end=arr.length;
int start=0;
int out=quicksearch(start,end-1);
return out;
}

public int quicksearch(int low, int high){
int pivot=numbers[low+(low+high)/2];
int i=low;int j=high;
while(i<j){
if(numbers[i]<pivot)
i++;
if(numbers[j]>pivot)
j--;
if(i<=j){
exchange(i,j);
i++;j--;
}
}
if(numbers[numbers.length-1]==pivot)
return pivot;
else{
if(low<i){
quicksearch(low,j);
}
if(i<high){
quicksearch(i,high);
}
}

}

}

skyboard

Posts : 31
Join date : 2011-09-03

View user profile

Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum