I am trying to implement selection sort recursively in java, but my program keeps throwing an ArrayIndexOutOfBounds exception. Not sure what I am doing wrong. Recursion is very hard for me. Please help! I am a beginner.
public static int[] selection(int[] array) {
return sRec(array, array.length - 1, 0);
}
private static int[] sRec(int[] array, int length, int current) {
if (length == current) { //last index of array = index we are at
return array; //it's sorted
}
else {
int index = findBig(array, length, current, 0);
int[] swapped = swap(array, index, length - current);
return sRec(swapped, length - 1, current);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
}
private static int findBig(int[] array, int length, int current, int biggestIndex) {
if (length == current) {
return biggestIndex;
}
else if (array[biggestIndex] < array[current]) {
return findBig(array, length, current + 1, current);
}
else {
return findBig(array, length, current + 1, biggestIndex);
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
Try changing this in your Swap method :
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
to this :
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
You have already gotten the value you want to assign to the array , when you add that to the array it is searching in that specific index ,
For Example :
You wanted to enter the value 8 to your Array
Instead of doing
array[index] = 8
You were doing
array[index] = array[8]
That was causing your OutOfBounds Exception.
I tested your code and it did not sort even after having fixed the "Out Of bound Exception". I've changed your method findBig in order to make it work. The principle is :
If the length of the sub array is one (begin==end) then the biggest element is array[begin]
divide the array by half
Recusively find the index of the biggest element in the left side
Recursively find the index if the biggest element in the right side
Compare the biggest element of the left side with that of the right side of the array and return the index of the biggest of both.
This leads to the following code which sort the array in a decreasing order:
public class Sort {
public static int[] selection(int[] array) {
return sRec(array,0);
}
private static int[] sRec(int[] array, int current) {
if (current == array.length-1) { //last index of array = index we are at
return array; //it's sorted
}
else {
int indexOfBiggest = findBig(array, current,array.length-1);
int[] swapped = swap(array, indexOfBiggest, current );
return sRec(swapped, current+1);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
}
private static int findBig(int[] array, int begin, int end) {
if (begin < end) {
int middle = (begin+end)/2;
int biggestLeft = findBig(array,begin,middle);
int biggestRight = findBig(array,middle+1,end);
if(array[biggestLeft] > array[biggestRight]) {
return biggestLeft;
}else {
return biggestRight;
}
}else {
return begin;
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
// System.out.println(findBig(array,0,array.length-1));
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
}
Related
running into a silly error and I just don't see it. I've been looking at this for a while and don't see what I'm missing. I am recursively searching an array for a specific target number but once I get up to element [7] it begins returning -1. Thanks for taking a look fellas/ladies!
public static void main(String[] args)
{
int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
Arrays.sort(a);
int target = a[7];
int first = a[0];
int last = a.length;
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n"+binarySearch(target,first,last,a));
}
public static int binarySearch(int target,int first, int last, int[] a)
{
int result;
if(first>last)
return -1;
else
{
int mid = (first+last)/2;
if(target == mid)
result = mid;
else if(target<a[mid])
result = binarySearch(target,first,last-1,a);
else
result = binarySearch(target,mid+1,last,a);
}
return result;
}
In several places you fail to accurately distinguish between the value in an index of an array and the index itself.
This: a[i] gets the value at the ith element
This: i is simply an index, i
With that in mind, here is a fixed version of your code. See my comments in the code for some specific errors I fixed:
public static void main(String[] args)
{
int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
Arrays.sort(a);
int target = a[7];
//here you want the index of the first location to search, not the value in that index
//so you use 0 instead of a[0]
int first = 0;
//the last element index is length-1, not length, since arrays are 0-based
int last = a.length - 1;
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n"+binarySearch(target,first,last,a));
}
public static int binarySearch(int target,int first, int last, int[] a)
{
int result;
if(first>last)
return -1;
else
{
int mid = (first+last)/2;
//here you need to check if the target is equal to the value at the index mid
//before you were checking if the target was equal to the index, which was never true
if(target == a[mid])
//you want to return the value at the target, not the index of the target
//so use a[mid] not mid
result = a[mid];
else if(target<a[mid])
//here you want to search from first to mid-1
//before you were searching from first to last-1, which is not correct binary search
result = binarySearch(target,first,mid - 1,a);
else
result = binarySearch(target,mid + 1,last,a);
}
return result;
}
public int thirdLargest(int[] arr){
int f_l = arr[0];
int s_l = arr[0];
int t_l = arr[0];
for(int i=1;i<arr.length;i++)
{
if (f_l < arr[i]){
t_l = s_l;
s_l = f_l;
f_l = arr[i];
}
else if (s_l < arr[i]){
t_l = s_l;
s_l = arr[i];
}
else if (t_l < arr[i]){
t_l = arr[i];
}
}
return t_l;
}
my code didn't passes some cases,any suggestion?
parameter {24,27,30,31,34,37,40,42}' , passes
parameter {2,-1,-2,-3,-4,-5}' , fails
This is simply cause by the fact that you initialize all values to arr[0]. If all elements are smaller than arr[0] this code won't update the values, even though the second-largest element for example wouldn't be arr[0]. Instead initialize the variables for the third/second/largest value with Integer.MIN_VALUE and start the search with the first element (index = 0) instead of the second.
There is actually a well-known algorithm for this, which is more generic than yours. It is called quick-select and looks like a quick sort with an optimization making it faster (linear time in average) : since we don't need to sort the array, we just recurse on the part of the array containing the index we are looking for (in your case, third item so index 2).
Here is an implementation in Java :
private static final Random rd = new Random();
public static int kthElement(int[] arr, int k) {
return kthElement(arr,k,0,arr.length);
}
private static T kthElement(int[] arr, int k, int min, int max) {
if (min < max - 1) {
int p = pivot(arr,min,max);
return p == k - 1 ? arr[p] :
p < k - 1 ? kthElement(arr,k,p + 1,max) : kthElement(arr,k,min,p);
}
return arr[min];
}
private static int pivot(int[] arr, int min, int max) {
int pivot = min + rd.nextInt(max - min);
swap(arr,pivot,max - 1);
pivot = min;
for (int i=min ; i<max ; i++)
if (arr[i] < arr[max - 1]) swap(arr,i,pivot++);
swap(arr,max - 1,pivot);
return pivot;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
Well, as an alternative to your working code, here is a solution that will allow you to find the Nth largest integer in your array using Collections to do the heavy lifting:
import java.util.Arrays;
import java.util.Collections;
public class ArrayNthLargest {
public static int getNthLargest(int[] arrayInput, int n) {
Integer[] sortedArray = new Integer[arrayInput.length];
for (int i = 0; i < arrayInput.length; i++) {
sortedArray[i] = new Integer(arrayInput[i]);
}
Arrays.sort(sortedArray, Collections.reverseOrder());
return (sortedArray[n - 1]);
}
public static void main(String[] args){
int nth = new Integer(0);
int n = new Integer(3);
int[] testArray = {1,2,3,4,5,6,23,44,55,8,1};
nth = getNthLargest(testArray, n);
System.out.printf("The %d sorted array value is %d", n, nth);
}
}
This was actually an interesting question to me to do in O(n) complexity. I hope this solution is order n. I used an ArrayList as a stack (since Stack object won't allow addition of items in specific incidences (I've generalized it).
public int thirdLargest(int[] arr){
public int N_TH = 3; // Assuming this is nth largest you want
public ArrayList<Integer> largest = new ArrayList<Integer>(N_TH);
for(int i = 0;i<N_TH;i++)
largest.add(0); // initialize the ArrayList
for(int i = 0;i<arr.length;i++) {
for(int j=0;j<largest.size();j++){
if(arr[i] >= largest.get(j)) {
// Add the item at the correct index
// Pop the last element
largest.remove(largest.size()-1);
largest.add(j,arr[i]);
break;
}
}
}
return largest.get(N_TH);
}
Let me know if you find any problems with it, I might have mistyped part of trying to put it in OP's method.
EDIT won't work with negative numbers at the moment. You can find the smallest value in arr and initialize largest with that value. Then it'll also with negative numbers
//as the title says, i need to find the index of the largest value in an int //array, all of this needs to be done in one method this is what my helper //method looks like so far
it only returns last index in array i can easily return the max value but i cant figure out how to return the index of that value
//this is helper method
private int recursiveGetIndexOfLargest( int[] list, int count )
{
int index;
int[] y = list;
int temp = count - 1;
if( count > 0 )
{
index = Math.max( list[list.length - 1], list[temp] );
for(int x = 0; x < y.length; x++)
{
if(y[x] == index)
{
return x;
}
}
return recursiveGetIndexOfLargest(list, temp);
}
else
{
return -1;//empty list
}
}
this is method that calls helper
public int getIndexOfLargest()
{
return recursiveGetIndexOfLargest(list, count);
}
Try this one:
int recursiveGetIndexOfLargest(int[] list, int count)
{
if (count == list.length - 1) return count;
int index = recursiveGetIndexOfLargest(list, count + 1);
return list[count] > list[index] ? count : index;
}
int[] arr = {1, 5, 2, 3, 0};
System.out.println(recursiveGetIndexOfLargest(arr, 0));
int findLargestIndex(int[] array, int currentPos, int currentLargestIndex)
{
if(currentPos == array.length)
return currentLargestIndex;
if(array[currentPost] > array[currentLargestIndex]
return findLargestIndex(array,currentPos+1, currentPos);
else
return findLargestIndex(array,currentPos+1, currentLargestIndex);
}
It is actually a O(n) for loop done recursively.
You start it like this:
int result = findLargestIndex(array,0,0);
This would work but it will alter the array.
void findLargestIndex(int[] array, int currentPos)
{
if(currentPos == array.size()) return;
array[0] = (array[currentPos] < array[currenPos + 1] ? currentPos + 1 : currentPos;
findLargestIndex(int[] array, currentPos + 1);
}
The largest index will be storred at array[0] (This alters the array).
You simply start the function:
findLargestIndex(array,0);
Thank You tomse!!!!!!!!
the parameter count is actually the size of the array so i changed it a little to
private int recursiveGetIndexOfLargest( int[] list, int count )
{
int index;
int temp = count - 1;
if( temp == 0 )
{
return temp;
}
else
{
index = recursiveGetIndexOfLargest(list, temp);
return list[temp] > list[index] ? temp : index;
}
}
and now it works damn i wasted several hours failing
For one of the questions i was asked to solve, I found the max value of an array using a for loop, so i tried to find it using recursion and this is what I came up with:
public static int findMax(int[] a, int head, int last) {
int max = 0;
if (head == last) {
return a[head];
} else if (a[head] < a[last]) {
return findMax(a, head + 1, last);
} else {
return a[head];
}
}
So it works fine and gets the max value, but my question is : is it ok to have for the base case return a[head] and for the case when the value at the head is > the value at last?
You could just as easily do it with only one counter, just the index of the value you want to compare this time:
public static int findMax(int[] a, int index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index-1))
} else {
return a[0];
}
}
This much better shows what is going on, and uses the default "recursion" layout, e.g. with a common base step. Initial call is by doing findMax(a, a.length-1).
It's actually much simpler than that. The base case is if you've reached the end of the array (the 'else' part of the ternary control block below). Otherwise you return the max of the current and the recursive call.
public static int findMax(int[] a) {
return findMax(a, 0);
}
private static int findMax(int[] a, int i) {
return i < a.length
? Math.max(a[i], findMax(a, i + 1))
: Integer.MIN_VALUE;
}
At each element, you return the larger of the current element, and all of the elements with a greater index. Integer.MIN_VALUE will be returned only on empty arrays. This runs in linear time.
I would solve this by dividing the array in to the half on each recursive call.
findMax(int[] data, int a, int b)
where a and b are array indices.
The stop condition is when b - a <= 1, then they are neighbours and the max is max(a,b);
The initial call:
findMax(int[] data, int 0, data.length -1);
This reduces the maximum recursion depth from N to log2(N).
But the search effort still stays O(N).
This would result in
int findMax(int[] data, int a, int b) {
if (b - a <= 1) {
return Math.max(data[a], data[b]);
} else {
int mid = (a+b) /2; // this can overflow for values near Integer.Max: can be solved by a + (b-a) / 2;
int leftMax = findMax(a, mid);
int rightMax = findMax(mid +1, b);
return Math.max(leftMax, rightMax);
}
}
I came across this thread and it helped me a lot. Attached is my complete code in both recursion and divide&conquer cases.
The run time for divide&conquer is slightly better than recursion.
//use divide and conquer.
public int findMaxDivideConquer(int[] arr){
return findMaxDivideConquerHelper(arr, 0, arr.length-1);
}
private int findMaxDivideConquerHelper(int[] arr, int start, int end){
//base case
if(end - start <= 1) return Math.max(arr[start], arr[end]);
//divide
int mid = start + ( end - start )/2;
int leftMax =findMaxDivideConquerHelper(arr, start, mid);
int rightMax =findMaxDivideConquerHelper(arr, mid+1, end);
//conquer
return Math.max( leftMax, rightMax );
}
// use recursion. return the max of the current and recursive call
public int findMaxRec(int[] arr){
return findMaxRec(arr, 0);
}
private int findMaxRec(int[] arr, int i){
if (i == arr.length) {
return Integer.MIN_VALUE;
}
return Math.max(arr[i], findMaxRec(arr, i+1));
}
What about this one ?
public static int maxElement(int[] a, int index, int max) {
int largest = max;
while (index < a.length-1) {
//If current is the first element then override largest
if (index == 0) {
largest = a[0];
}
if (largest < a[index+1]) {
largest = a[index+1];
System.out.println("New Largest : " + largest); //Just to track the change in largest value
}
maxElement(a,index+1,largest);
}
return largest;
}
I know its an old Thread, but maybe this helps!
public static int max(int[] a, int n) {
if(n < 0) {
return Integer.MIN_VALUE;
}
return Math.max(a[n-1], max(a, n - 2));
}
class Test
{
int high;
int arr[];
int n;
Test()
{
n=5;
arr = new int[n];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
high = arr[0];
}
public static void main(String[] args)
{
Test t = new Test();
t.findHigh(0);
t.printHigh();
}
public void printHigh()
{
System.out.println("highest = "+high);
}
public void findHigh(int i)
{
if(i > n-1)
{
return;
}
if(arr[i] > high)
{
high = arr[i];
}
findHigh(i+1);
return;
}
}
You can do it recursively as follows.
Recurrent relation it something like this.
f(a,n) = a[n] if n == size
= f(a,n+1) if n != size
Implementation is as follows.
private static int getMaxRecursive(int[] arr,int pos) {
if(pos == (arr.length-1)) {
return arr[pos];
} else {
return Math.max(arr[pos], getMaxRecursive(arr, pos+1));
}
}
and call will look like this
int maxElement = getMaxRecursive(arr,0);
its not okay!
your code will not find the maximum element in the array, it will only return the element that has a higher value than the elements next to it, to solve this problem,the maximum value element in the range can be passed as argument for the recursive method.
private static int findMax(int[] a, int head, int last,int max) {
if(last == head) {
return max;
}
else if (a[head] > a[last]) {
max = a[head];
return findMax(a, head, last - 1, max);
} else {
max = a[last];
return findMax(a, head + 1, last, max);
}
}
Optimized solution
public class Test1 {
public static int findMax(int[] a, int head, int last) {
int max = 0, max1 = 0;
if (head == last) {
return a[head];
} else if (a[head] < a[last]) {
max = findMax(a, head + 1, last);
} else
max = findMax(a, head, last - 1);
if (max >= max1) {
max1 = max;
}
return max1;
}
public static void main(String[] args) {
int arr[] = {1001, 0, 2, 1002, 2500, 3, 1000, 7, 5, 100};
int i = findMax(arr, 0, 9);
System.out.println(i);
}
}
Thanks #Robert Columbia for the suggestion!
Update: This following function is going to recursively start from index 0 and it will keep adding to this index value till it's equal to the Length of the array, if it's more we should stop and return 0. Once we're doing that, we need to get the max of every two items in the array so, for example:
A = [1 , 2 , 3 ];
A[0] ( 1 ) vs A[1] ( 2 ) = 2
A[1] ( 2 ) vs A[2] ( 3 ) = 3
Max(2,3) = 3 ( The answer )
public int GetMax(int [] A, int index) {
index += 1;
if (index >= A.Length) return 0;
return Math.Max(A[index], GetMax(A, index + 1));
}
static int maximumOFArray(int[] array,int n) {
int max=Integer.MIN_VALUE;
if(n==1) return array[0];
else
max=maximumOFArray(array, --n);
max= max>array[n] ? max : array[n];
return max;
}
private static int getMax(int [] arr, int idx) {
if (idx==arr.length-1 ) return arr[idx];
return Math.max(arr[idx], getMax (arr,idx+1 ));
}
public class FindMaxArrayNumber {
public static int findByIteration(int[] array) {
int max = array[0];
for (int j : array) {
max = Math.max(j, max);
}
return max;
}
public static int findByRecursion(int[] array, int index) {
return index > 0
? Math.max(array[index], findByRecursion(array, index - 1))
: array[0];
}
public static void main(String[] args) {
int[] array = new int[]{1, 2, 12, 3, 4, 5, 6};
int maxNumberByIteration = findByIteration(array);
int maxNumberByRecursion = findByRecursion(array, array.length - 1);
System.out.println("maxNumberByIteration: " + maxNumberByIteration);
System.out.println("maxNumberByRecursion: " + maxNumberByRecursion);
// Outputs:
// maxNumberByIteration: 12
// maxNumberByRecursion: 12
}
}
int maximum = getMaxValue ( arr[arr.length - 1 ], arr, arr.length - 1 );
public static int getMaxValue ( int max, int arr[], int index )
{
if ( index < 0 )
return max;
if ( max < arr[index] )
max = arr[index];
return getMaxValue ( max, arr, index - 1 );
}
I felt that using a tracker for current maximum value would be good.
How can i implement a recursive binary search in an int array using only 1 parameter in java ?
it tried but my code doesn't work. I implemented a class which its instances are objects having arrays and a count variable to detect how many elements are their in the array. any idea how can i implement the recursive binary search using only 1 parameter ?
public class LinearSortedArray {
int count;
int[] a;
public LinearSortedArray() {
count = 0;
}
public LinearSortedArray(int size) {
count = 0;
a = new int[size];
}
public static int[] copyingMethod(int startPoint, int endPoint,
LinearSortedArray arrayObj) {
int[] copyingArray = new int[endPoint - startPoint];
int j = startPoint;
for (int i = 0; i < copyingArray.length; i++) {
copyingArray[i] = arrayObj.a[j];
j++;
}
return copyingArray;
}
public int binarySearchRec(int x) {
if (count == 0) {
return -1;
}
int pivot = count / 2;
LinearSortedArray newArrayObj;
if (x > a[pivot]) {
newArrayObj = new LinearSortedArray(count - pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(pivot, count, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return pivot + newArrayObj.binarySearchRec(x);
} else if (x < a[pivot]) {
newArrayObj = new LinearSortedArray(pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(0, pivot, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return newArrayObj.binarySearchRec(x);
} else {
return pivot;
}
}
}
P.S.: The arrays are already sorted
Binary search really requires a range and a target value -- so if you're only passing one parameter, this has to be the target and this must encapsulate the array & range.
public class ArraySegment {
protected int[] array;
protected int boundLo;
protected int boundHi;
public class ArraySegment (int[] array) {
// entire array.
this( array, 0, array.length);
}
public class ArraySegment (int[] array, int lo, int hi) {
this.array = array;
this.boundLo = lo;
this.boundHi = hi;
}
public int binarySearch (int target) {
if (boundHi <= boundLo) {
return -1; // Empty; not found.
}
int pivot = (boundLo + boundHi) / 2;
int pivotEl = array[ pivot];
if (target == pivotEl) {
return pivot; // Found!
}
if (target < pivotEl) {
// recurse Left of pivot.
ArraySegment sub = new ArraySegment( array, boundLo, pivot);
return sub.binarySearch( target);
} else {
// recurse Right of pivot.
ArraySegment sub = new ArraySegment( array, pivot, boundHi);
return sub.binarySearch( target);
}
}
}
It's a little bit questionable what kind of result you should return -- there isn't a good answer with the question posed like this, as an "integer index" kinda defeats the purpose of the ArraySegment/ range wrapper, and returning an ArraySegment containing only the found value is also fairly useless.
PS: You really shouldn't be copying the array or it's contents, just passing round references to ranges on that array. Like java.lang.String is a range on a character array.
You could contrive a single-parameter by using the Value Object Pattern, where you pass one "wrapper" object, but the object has many fields.
For example:
class SearchParams {
int target;
int start;
int end;
SearchParams(t, s, e) {
target = t;
start = s;
end = e'
}
}
int search(SearchParams params) {
// some impl
return search(new SearchParams(params.target, a, b));
}
Technically, this is one parameter. Although it may not be in the spirit of the rules.