I have a problem of using an insert method and reverse method that i am trying to make within a constructor as i am new and this is an exercise example. For the inserting constructor i have:
It is supposed to insert an element at index in the array
public boolean insert(int index, int element)
{
int i;
newArray = new int[Array.length + 1];
for(i = index; i > newArray.length - 1; i++)
{
newArray[i] = newArray[i + 1];
for(i = 0; i < newArray.length + 1; i++)
{
Array[i] = newArray[i];
}
}
Array[index] = element;
numElement = numElement + 1;
return true;
and my reverse constructor is:
public boolean reverse(int start, int end)
{
int temp;
for(int i = start; i <(start + end) / 2 ; i++)
{
temp = Array[i];
Array[i] = Array[end - i];
Array[end - i] = temp;
}
return true;
}
when i use the insert constructor it would replace the number and not make a new array to accomodate the extra element and before the output closes it would give me an exception error. For the reverse, it would not give me the correct output. Eg: i have an array [1,2,3,4,5,6,7,8,9,10] and i want to reverse numbers 3-7 it would output [1,2,6,5,4,3,7,8,9,10]. I don't know what could be wrong with the code.
EDIT: Also i am trying not to use any Arrays.util methods/ArrayList and such
There is a Java reverse method for arrays:
ArrayUtils.reverse(int[] array) //Reverses the order of the given array.
And also for add:
ArrayUtils.add(int[] array, int element) //Copies the given array and adds the given element at the end of the new array.
If not using ArrayUtils (why not?), then perhaps use System.arraycopy for the insert method.
Also, these are not constructors, they are methods. They probably should also be void methods or return the new array and not a boolean (unless there is a reason to return a boolean here?).
Example insert method using System.arraycopy:
public static int[] insert(int[] list, int position, int value)
{
int[] result = new int[list.length + 1];
System.arraycopy(list,0,result,0,position);
result[position] = value;
System.arraycopy(list,position,result,position + 1,list.length - position);
return result;
}
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
So, I am trying to get my binarySearch to work and it dos not return the proper search item. Anyone have an idea? It always returns close to the item though.I know the issue is specifically with the while loop in the binarySearch method.
public class Sort {
static int item;
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] list = new int[500];
for (int c = 0; c < 500; c++){
Random r = new Random();
list[c] = r.nextInt(1000);
}
int l = list.length;
System.out.print("Enter a search element: ");
System.out.println();
item = console.nextInt();
insertionSort(list, l);
}
public static int binarySearch(int[] list, int l,
int searchItem){
int first = 0;
int last = l - 1;
int mid = 0;
boolean found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == searchItem)
found = true;
else if (list[mid] > searchItem)
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
else
return 0;
}
public static void insertionSort(int[] list, int l){
int first, location;
int temp;
for (first = 1; first < l; first++){
if (list[first] < list[first - 1]){
temp = list[first];
location = first;
do {
list[location] = list[location - 1];
location--;
}
while(location > 0 && list[location - 1] > temp);
list[location] = temp;
}
}
System.out.println(binarySearch(list, l, item));
}
}
Thanks for the help!
You need to return mid + 1 as index start from 0.
So if you have 1,2,3 element and if you try to find 2, it will return 1 as array[1] points to 2. So if you return 2 it will mean that you found the element at second location.
Your issue lies here:
if (found)
return mid;
Say you have an array with numbers {1,2,3,4,5}
According to the way array indices get assigned 1 will get the index of 0, 2 will get the index of 1 and so on.
when you try to search for 2 and you find it, the value of mid(according to the program) holds the index of value 2 in the array. The index of 2 in the above array is 1. So instead of returning the index of 2, you just need to return the item itself.
if (found)
return list[mid];
I would say better design would be to return true/false from the binary search routine to indicate whether the item was found or not. The reason being you return 0 as the case where you never find the item in the array which becomes problematic if 0 is also included in the values to search.
If you were trying to return the index of item once found instead of the item itself, then your program functions as expected other than the case where it wasn't found - it should return something like an index of -1 and not 0(a valid index).
else
return 0;
I'm trying to count and output the number of swaps of data elements in a bubble sort method using Java. I'm a beginner, so am unsure how to overcome my issue: method is void and can't return anything, so what can I do to output the swaps?
in one doc, the sort method:
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
//Bubble sort algorithm.
//Postcondition: list objects are in ascending order.
public void bubbleSort(T list[], int length)
{
//Initialize swap counter
int bubbleSwaps = 0;
for (int iteration = 1; iteration < length; iteration++)
{
for (int index = 0; index < length - iteration;
index++)
{
Comparable<T> compElem =
(Comparable<T>) list[index];
if (compElem.compareTo(list[index + 1]) > 0)
{
T temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
bubbleSwaps++;
}
}
}
}
}
In another, I use the method, and am looking to find a way to output bubbleSwaps:
public class numberSwapsReview{
public static void main(String [] args)
{
// define an Integer array of 1000 elements
Integer[] bubbleArray = new Integer[1000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*1000)
for (int i = 0; i < bubbleArray.length; i++) {
bubbleArray[i] = (int)(Math.random() * 1000);
}
SearchSortAlgorithms<Integer> sortObject = new SearchSortAlgorithms<Integer>();
sortObject.bubbleSort(bubbleArray, 1000);
}
}
Since you are making an instance of the class, you could make bubbleSwaps class level then get the value after the sort
public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
//Initialize swap counter
int bubbleSwaps = 0;
//Bubble sort algorithm.
//Postcondition: list objects are in ascending order.
public void bubbleSort(T list[], int length)
{
for (int iteration = 1; iteration < length; iteration++)
{
for (int index = 0; index < length - iteration;
index++)
{
Comparable<T> compElem =
(Comparable<T>) list[index];
if (compElem.compareTo(list[index + 1]) > 0)
{
T temp = list[index];
list[index] = list[index + 1];
list[index + 1] = temp;
this.bubbleSwaps++;
}
}
}
}
public int getBubbleSwaps(){
return this.bubbleSwaps;
}
}
Here is the other class:
public class numberSwapsReview{
public static void main(String [] args)
{
// define an Integer array of 1000 elements
Integer[] bubbleArray = new Integer[1000];
// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*1000)
for (int i = 0; i < bubbleArray.length; i++) {
bubbleArray[i] = (int)(Math.random() * 1000);
}
SearchSortAlgorithms<Integer> sortObject = new SearchSortAlgorithms<Integer>();
sortObject.bubbleSort(bubbleArray, 1000);
sortObject.getBubbleSwaps();
}
}
You might use a Comparator instead of Comparable elements. With that (preferable as a wrapper around the normal comparator), you can compute in a field variable how many time was the result >0
One way would be to change the return type of your method as int and return the number of swaps you did. Then just call:
int nbswaps = sortObject.bubbleSort(bubbleArray, 1000);
If you can't modify the return type, you can
print the number of swaps in the method at the end
create an attribute named nbSwaps in your class (don't forget to reset it at each call of bubbleSort method) and then implement a getter to be able to get the value from your main
Also you may change the declaration of your class as class SearchSortAlgorithms<T extends Comparable<T>>.
Now you will be sure that the elements have to be comparable and you could get rid of Comparable<T> compElem = (Comparable<T>) list[index];.
I have an array, let's say: LRU_frame[] = {4,1,0,3}
I have a random() function that spits out a random number. If the random number n is contained in the array LRU_frame, then, n should be on LRU_frame[0] and everything else must be shifted down accordingly.
For example if random() gives me a 0, the new LRU_frame[] = {0,4,1,3}
Another example, if random() gives me a 3, the new LRU_frame[] = {3,4,1,0}
How do I do this for any Array size with any number of elements in it?
I know how to shift arrays by adding a new element on LRU_frame[0] but have no idea on how to re-organize the array like I need.
This is the code I have so far and let's assume char a is the random number(casted into char) to use and re-organize the array.
public static void LRU_shiftPageRef(char a) {
for (int i = (LRU_frame.length - 2); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
You have a good idea, you only need to find the position of the a element in the array and start the cycle from it, instead of LRU_frame.length.
int index = -1;
// find the positon of 'a' in the array
for (int i = 0; i <= (LRU_frame.length - 1); i++) {
if (LRU_frame[i] == a) {
index = i;
break;
}
}
// if it is present, do roughly the same thing as before
if (index > -1) {
for (int i = (index - 1); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
However if you can use ArrayLists it gets much easier.
// declaration
ArrayList<Integer> LRU_frame = new ArrayList<Integer>();
...
if (LRU_frame.contains(a)) {
LRU_frame.remove((Integer) a);
LRU_frame.add(0, a);
}
I think this could be the sort of thing you are after:
public static void LRU_shiftPageRef(char a) {
int index = indexOf(a);
if (index == -1) {
//not currently in array so create a new array 1 bigger than existing with a in newArray[0] or ignore depending on functionality required.
} else if (index > 0) {
//Set first entry as a and shift existing entries right
char insertChar = a;
char nextChar = LRU_frame[0];
for (int i =0; i < index; i++) {
LRU_frame[i] = insertChar;
insertChar = nextChar;
nextChar = LRU_frame[i+1];
}
LRU_frame[index] = insertChar;
} else {
//do nothing a is already at first position
}
}
public static int indexOf(char a) {
for (int i=0; i < LRU_frame.length; i++) {
if (LRU_frame[i] == a) {
return i;
}
}
return -1;
}
Use Arrays.sort(LRU_frame); to sort the entire array, or Arrays.sort(LRU_frame, fromIndex, toIndex)); to sort part of the array.
Arrays class has other useful methods like copyOfRange.