How to remove an Integer from an Array Java - java

I am a newbie in Java programming and I have a trouble in my program.
I have an array and i want to extract the max integer from it and return it to the main program. But without using ArrayList.
I must not have 0 in this certain position when i print it so I cant just replace it. Take a look at what i did so far but i think that it is so wrong.
public int extractMax()
{
for (int i = 0; i < size; i++)
{
if(maxInsert == Queue[i])
{
Queue[i] = null;
return maxInsert;
}
} return -1;
}

You cannot assign null if the array in a an array of primitives, you would see an error like this :
cannot convert from null to int
If the array is an array of objects (Integer for example), then assigning it to null would work, but I would suggest if you need to manipulate the entries of your array that you use a List instead.
For example :
List<Integer> integers = new ArrayList<>(Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10}));
System.out.println(integers.size());
integers.remove(new Integer(3));
System.out.println(integers.size());
Would print :
10
9

So the logic here is to basically iterate through every element of the array to see if there is an element greater than the current greatest element (starts at the first element) in the array. If a greater element is found, then the max variable is reset to this new value and the loop carries on. If an even greater element is found, then the same thing happens by updating the max variable. To actually remove this element from the array, you can create a new array with a size of one less than the original size, copy all the elements up to the max into the new array, and shift all the elements to the right of the max by to the left by one. This is what it should look like.
public int extractMax()
{
maxInsert = Queue[0];
int maxIndex = 0;
for (int i = 1; i < size; i++)//get the location of the max element
{
if(maxInsert < Queue[i])
{
maxInsert = Queue[i];
maxIndex = i;
}
}
int[] temp = new int[Queue.length - 1];
for(int j = 0; j < maxIndex; j++){ //adding elements up until the max
temp[j] = Queue[j];
}
for(int k = maxIndex; k < temp.length; k++){ //adding elements after the max
temp[k] = Queue[k+1];
}
Queue = temp; //queue is now this new array we've just made
return maxInsert;
}

Basically you can not remove an element from an Array like in List objects. So create a new Array and add all elements in Queue except the bigger one to the new Array. And lastly, assign the new array to the Queue. Here is an example code:
public int extractMax()
{
for (int i = 0; i < size; i++)
{
if(maxInsert == Queue[i])
{
removeFromArray(i);
return maxInsert;
}
} return -1;
}
private void removeFromArray(int i) {
int[] newQueue = new int[Queue.length-1];
int k = 0;
for (int j = 0; j < newQueue.length; j++,k++) {
if(i == j) {
k++;
}
newQueue[j] = Queue[k];
}
Queue = newQueue;
}

Related

How do I sort an array of integers from minimum to maximum value without using Arrays.sort()?

I'm learning how to use arrays, and I'm trying to manually sort an array of integers using two ArrayList<Integer>.
Here's what I have currently:
public Object[] arraySort (int[] importedArray) {
// !!! This method returns the original imported method (?). !!!
ArrayList<Integer> unsorted = new ArrayList<>();
ArrayList<Integer> sorted = new ArrayList<>();
// Convert importedArray into unsorted Integer ArrayList
for (int i = 0; i < importedArray.length; i++) {
unsorted.add(importedArray[i]);
}
// Find minimum value of unsorted ArrayList, add to sorted ArrayList, and remove min value from unsorted
for (int i = 0; i < unsorted.size(); i++) {
int min = Integer.MAX_VALUE;
int index = 0;
for (int j = 0; j < unsorted.size(); j++) {
if (unsorted.get(j) < min) {
min = unsorted.get(j);
index = j;
}
}
unsorted.remove(index);
sorted.add(min);
}
return unsorted.toArray();
}
However, when I run the method, I get the same imported array back. The first for loop to convert int[] into ArrayList<Integer> apparently worked when I checked using print, so the problem is most likely in the second for loop.
I've also tried other insertion sorting methods, but I'm not sure what I am doing wrong with this type of sorting method. Did I totally screw up somewhere? Or is this method not possible? Thanks in advance for your help!
First of all, you should return the sorted array and not the unsorted one. You should also be careful when using unsorted.size() in the loop header because the programm will call that method every time an iteration has finished. But since you decrease the size inside of the loop with update.remove(index), the size does not stay the same and you just skip some values. Thus, you should save that value in a variable before starting the loop. The following code worked for me:
public Object[] arraySort(int[] importedArray) {
ArrayList<Integer> unsorted = new ArrayList<>();
ArrayList<Integer> sorted = new ArrayList<>();
for (int i = 0; i < importedArray.length; i++) {
unsorted.add(importedArray[i]);
}
int size = unsorted.size();
for (int i = 0; i < size; i++) {
int min = Integer.MAX_VALUE;
int index = 0;
for (int j = 0; j < unsorted.size(); j++) {
if (unsorted.get(j) < min) {
min = unsorted.get(j);
index = j;
}
}
unsorted.remove(index);
sorted.add(min);
}
return sorted.toArray();
}

How do I remove the item with the highest value in an unsorted array?

So right now I am trying to code a function that will remove the highest value in an unsorted array.
Currently the code looks like this:
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
}
/*int max = array.get(0);
for (int i = 1; i < array.length; i++) {
if (array.get(i) > max) {
max = array.get(i);
}*/
}
tailIndex = tailIndex - 1;
}
Here I have my attempt at this:
int priority = 0;
for (int i = 1; i < tailIndex; i++) {
while (i > 0 && ((PriorityItem<T>) storage[i - 1]).getPriority() < priority)
storage[i] = storage[i + 1];
i = i - 1;
The program runs no bother but still deletes the first item in the array instead of the highest number. This code was given my my college lecturer for a different solution but unfortunately it doesn't work here.
Would this solution work with enough altercations? Or is there another solution I should try?
Thanks.
The code snippet in the question can be updated to below code, while keeping the same data structure i.e. queue and this updated code has 3 steps - finding the index of largest element, shifting the elements to overwrite the largest element and finally set the tailIndex to one less i.e. decrease the size of the queue.
#Override
public void remove() throws QueueUnderflowException {
if (isEmpty()) {
throw new QueueUnderflowException();
} else {
int priority = 0;
int largeIndex = 0;
for (int i = 0; i < tailIndex; i++) {
if (((PriorityItem<T>) storage[i]).getPriority() > priority) {
priority = ((PriorityItem<T>) storage[i]).getPriority();
largeIndex = i ;
}
}
for(int i = largeIndex; i < (tailIndex - 1) ; i++)
storage[i] = storage[i + 1];
}
tailIndex = tailIndex - 1;
}
Hope it helps.
Step 1
Find the highest index.
int[] array;
int highIndex = 0;
for (int i = 1; i < highIndex.size(); i++)
if (array[highIndex] < array[highIndex])
highIndex = i;
Step 2
Create new array with new int[array.size() - 1]
Step 3
Move all values of array into new array (except the highest one).
My hint: When its possible, then use a List. It reduces your complexity.
You can find the largest Number and it's index then copy each number to its preceding number. After that, you have two options:
Either add Length - 1 each time you iterate the array.
Or copy the previous array and don't include removed number in it.
Working Code:
import java.util.Arrays;
public class stackLargest
{
public static void main(String[] args)
{
int[] unsortedArray = {1,54,21,63,85,0,14,78,65,21,47,96,54,52};
int largestNumber = unsortedArray[0];
int removeIndex = 0;
// getting the largest number and its index
for(int i =0; i<unsortedArray.length;i++)
{
if(unsortedArray[i] > largestNumber)
{
largestNumber = unsortedArray[i];
removeIndex = i;
}
}
//removing the largest number
for(int i = removeIndex; i < unsortedArray.length -1; i++)
unsortedArray[i] = unsortedArray[i + 1];
// now you have two options either you can iterate one less than the array's size
// as we have deleted one element
// or you can copy the array to a new array and dont have to add " length - 1" when iterating through the array
// I am doing both at once, what you lke you can do
int[] removedArray = new int[unsortedArray.length-1];
for(int i =0; i<unsortedArray.length-1;i++)
{
System.out.printf(unsortedArray[i] + " ");
removedArray[i] = unsortedArray[i];
}
}
}
Note: Use List whenever possible, it will not only reduce complexity, but, comes with a very rich methods that will help you a big deal.

Java - iterate through ArrayList for only increasing elements

Here is my ArrayList:
[1,2,1,0,3,4]
I'm trying to return this:
[1,2,3,4]
Here is my current attempt:
for (int i = 0; i < myArray.size() - 1; i++) {
if (myArray.get(i) < myArray.get(i + 1)) {
System.out.println("Increasing sequence...");
}
}
However, this is not returning the desired output, any ideas?
You'll have to maintain an index (or value) of the last element that you had printed and store it in some variable. Then, you'll have to use the stored element for every new element and check if is greater than the stored element.
As you have mentioned, the first element has to be anyway printed, no matter what.
Something like this might work:
List<Integer> myArray = Arrays.asList(new Integer[]{1,2,1,0,3,4});
System.out.println(myArray.get(0));
int prevPrint = myArray.get(0);
for (int i = 1; i < myArray.size();i++) {
if (myArray.get(i) > prevPrint) {
System.out.println(myArray.get(i));
prevPrint = myArray.get(i);
}
}
The reason why your program was failing was because you were comparing the adjacent two values only and it was possible that you might have already printed a value which is greater than any of the two adjacent values.
A similar question, but a totally different approach (LIS) exists and can be found here
A slight variant on Parijat's answer to avoid repeating the System.out.println:
for (int j = 0; j < myArray.size();) {
System.out.println(myArray.get(j));
int start = j;
do {
++j;
while (j < myArray.size() && myArray.get(j) <= myArray.get(start));
}
Try this,
public static List<Integer> findIncreasingOrder(int[] nums) {
List<Integer> result = new ArrayList<>();
int MAX = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int value = nums[i];
if (value >MAX){
System.out.println(value);
MAX = value;
result.add(value);
}
}
return result;
}

Not able to add to ArrayList properly

I have 2 methods in my program, one to add ***** above and below the smallest int in the array and one to add %%%%% above and below the largest. The method for the largest is essentially the same as the other but for some reason isn't adding what is needed.
Here is the smallest element method:
public static ArrayList smallestElement() {
int smallest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] < smallest)
smallest = array[i];
String smallestString = String.valueOf(smallest);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
if (smallestString.equals(String.valueOf(array[i]))) {
list.add("*****");
list.add(Integer.toString(array[i]));
list.add("*****");
} else {
list.add(Integer.toString(array[i]));
}
}
return list;
}
Here is the method for the largest element:
public static ArrayList largestElement() {
int largest = array[0];
for (int i = 0; i < array.length; i++)
if (array[i] > largest)
largest = array[i];
String largestString = String.valueOf(largest);
for(int i = 0; i < array.length; i++) {
if (largestString.equals(String.valueOf(array[i]))) {
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
} else {
smallestElement().add(Integer.toString(array[i]));
}
}
System.out.println(smallestElement());
return smallestElement();
}
}
If anyone knows why this isn't performing correctly, I would really appreciate the help
You are creating a new object every time you are executing the smallestElement function. Instead do something like,
ArrayList<String> list = smallestElement();
Then use this list object every time you are calling smallestElement() method
You have already created the list 3 times over by this line
smallestElement().add("%%%%%");
smallestElement().add(Integer.toString(array[i]));
smallestElement().add("%%%%%");
Create just 1 list and use it instead of calling the smallestelementelement() function multiple times
You are overcomplicating things here. There is no need to turn that minimum array value into a string right there (and to then do String comparisons later on). Btw: those string comparisons are also your problem: your code will definitely not work when your minimal value shows up several times in your array - because your code will put in those patterns for each match!
Instead, you could do something like:
int indexToUse = 0;
for (int i = 0; i < array.length; i++) { // please always use braces!
if (array[i] < array[indexToUse]) {
indexToUse = i;
}
}
List<String> valuesWithMarkerStrings = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (i == indexToUse -1 || i == indexToUse+1) {
valuesWithMarkerStrings.add("******");
} else {
valuesWithMarkerStrings.add(Integer.toString(array[i]);
}
}
(where my solution assumes that you want to have *** ... instead of array[i] for such rows ... )

Sort an Integer Array and Store result with its index in Java

hello guys i need to sort some elements of integer in an integer array and need to store the index of the sorted list
assume if the elements in array are
x[]= {10,20,40,70,80,50,30};
i need to get the index of the sorted order say in this case i need to get 4,3,5,2,6,0 (ascending) (array x starting from 0)
A simple way (not algorithmically clever) would be to make a new list (or array) of objects from the existing list that contains the value and the index:
class ValueAndIndex implements Comparable<ValueAndIndex> {
final int value;
final int index;
ValueAndIndex(int value, int index) {
this.value = value;
this.index = index;
}
#Override public int compareTo(ValueAndIndex other) {
// compare on value;
if (this.value < other.value) {
return -1;
} else if (this.value > other.value) {
return 1;
} else {
return 0;
}
}
}
Now, create instances of this class in a list:
List<ValueAndIndex> secondaryList = new ArrayList<ValueAndIndex>(x.length);
for (int i = 0; i < x.length; ++i) {
secondaryList.add(new ValueAndIndex(x[i], i));
}
Sort this list:
Collections.sort(secondaryList);
Now, the indices are still in this list:
int [] indexesInSortedOrder = new int[x.length];
for (int i = 0; i < secondaryList.size(); ++i) {
indexesInSortedOrder[i] = secondaryList.get(i).index;
}
System.out.println(Arrays.toString(indexesInSortedOrder));
Possible solution
//sort the array intio a new array
y[] = x;
Arrays.sort(y); //sort ascending
//final array of indexes
int index_array[] = new int[7];
//iteretate on x arrat
for(int i=0; i<7; i++)
//search the position of a value of the original x array into the sorted y array, store the position in the index array
index_array[i] = arrays.binarySearch(x,y[i]);
you can create an array
y[] = {0,1,2,3,4,5,6};
And ith any sorting algorithm, when you switching moving two elements in array x, do the same in array y
One way to do (what I understand) you need:
Determine the size n of the original array.
Create result array R and initialize its elements with 0 . . n-1
Finally implement one sort algorithm in the way that it sorts a copy(!) of your original array whilst also switching the elements in R
Example run:
Copied Result
Array
------------------
1. 2-3-1 0-1-2
2. 2-1-3 0-2-1
3. 1-2-3 2-0-1
public Map sortDecendingDFSGlobal() {
Map<String, Object> multiValues = new HashMap<String, Object>();
double[] dfs = this.global_dfs;
int[] index = new int[dfs.length];
for (int i = 0; i < dfs.length; i++) {
index[i] = i;//for required indexing
}
for (int i = 0; i < dfs.length; i++) {
//sorting dfsglobal in decending order
double temp = dfs[i];
double swap = dfs[i];
int swapIndex = i;
//keeping track of changing indexing during sorting of dfsglobal
int indStart = index[i];
int indSwap = index[i];
int number = i;
for (int j = i; j < dfs.length; j++) {
if (temp < dfs[j]) {
temp = dfs[j];
swapIndex = j;
indSwap = index[j];
number = j;
}
}
dfs[i] = temp;
dfs[swapIndex] = swap;
index[i] = indSwap;
index[number] = indStart;
}
//again sorting the index matrix for exact indexing
for (int i = 0; i < index.length - 1; i++) {
for(int j = i; j < index.length - 1; j++ )
{
if(dfs[j] == dfs[j + 1] && index[j] > index[j + 1])
{
int temp = index[j];
index[j] = index[j+1];
index[j + 1] = temp;
}
}
}
this.sortedDFS = dfs;
this.arrIndex = index;
multiValues.put("sorted", dfs);
multiValues.put("index", index);
return multiValues;
} //SortedDecendingDFSGlobal()

Categories