finding the index of max and min in an array - java

This is my code. I am using the bluej IDE.
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i <= num.length - 1; i++){
if (num[i] < smallest) smallest = num[i];
if (num[i] > largest) largest = num[i];
}
for (int i = 0; i <= num.length - 1; i++){
if (num[i] != smallest) countsmall++;
if (num[i] != largest) countlarge++;
}
int array[] = {countsmall,countlarge};
return array;
}
}
I am trying to find the minimum and maximum value in an array which I successfully did. After that,I am trying to find its index. I created a variable count, and then went through the array. If that item in the array does not equal the minimum or maximum value, count+= count. However, for some reason its not working. The code compiles but returns the wrong value. Keep in mind I am not allowed to use java libraries. Any help would be much appreciated, thanks.

If you want also indexes of biggest and smallest, why dont you do it in one loop? eg:
public class practice
{
public int[] minMax(int[] num) {
int smallest = num[0];
int largest = num[0];
int countsmall = 0;
int countlarge = 0;
for (int i = 0; i < num.length; i++){
if (num[i] < smallest) {
smallest = num[i];
countsmall=i;
}
if (num[i] > largest) {
largest = num[i];
countlarge=i;
}
}
int array[] = {countsmall,countlarge};
return array;
}
}

Related

MaxElements of column

My question is how to find three largest elements in column of matrix. If there was about finding only largest element i would know, but here i have no idea. Here is my code for the largest element in column:
public static void Column(int m, int[][] arr)
{
for (int i = 0; i < m; i++) {
int max = arr[0][i];
for (int j = 1; j < arr[i].length; j++)
if (arr[j][i] > max)
max = arr[j][i];
System.out.println(max);
}
}
You need to reverse the i and j in the following pieces:
int max = arr[0][i];
if (arr[j][i] > max)
max = arr[j][i];
Also in the j loop the first value should be zero. if you wish to keep it at 1 then you should use <= as the conditional.

Index position of the smallest number in the array

I have a question about return the index position of the smallest number in the array. I picked out 3 answers from 5 answer were given that I provided below. I think one of them might possibly be correct. However, I quite don't understand the code very much, so I'm looking for an explanation how they work.
A
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return a[i];
}
B
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return i;
}
C
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[min]) {
min = i;
}
}
return min;
}
It is pretty straight forward.. you are looking for the smallest index.
Imagine array a has 3 elements.
A
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length, i++) {
if (a[i] < a[min]) {
min = i;
}
}
return a[i]; //returning value. Wrong!
//you are searching for the index, not value isnt' it?
}
B
public int min(int[] a) {
int min = 0;
for (int i = 1; i < a.length, i++) {
if (a[i] < a[min]) {
min = i;
}
}
return i; //returning i which only exist in for-loop scope. Wrong!
}
C
public int min(int[] a) { //assume a has 3 elements
int min = 0; //for storing smallest index
for (int i = 1; i < a.length, i++) { //loop index 1,2
if (a[i] < a[min]) { //if current array value < current smallest value
min = i; //store new found smallest index
}
}
return min; //returning min, the smallest index
}
If min is not updated through the looping, it means index 0 (default value of min) holds the smallest value. Option C will be the correct answer.
The first code will give an error (Index out of bound exception)because at the end of for loop your " i " will be equal to the length of array and you are returning a[i] so this solution is completely wrong. The second code will return the length of array so it is also wrong solution. The third code that you have entered will return the index of smallest value. So the solution is correct.

Writing a function that takes an array and returns only the positives

For my lab, I need to write a static function called getPositiveNumbers that takes an argument of int[] numbers, and returns a new array with only the positive numbers in that array. I know that I first need to count how many positive numbers are in the array, and then create a new array of that size. I'm wondering how should I go about filling that new array with only the positive numbers. Any help would be appreciated, as I'm really trying to learn java. The following is what I currently have written. Thanks!
public class Example1 {
public static int[] getPositiveNumbes(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i +=1)
{
if (numbers[i] > 0)
{
total += 1;
}
}
int[] nums = new int[total];
for ( int i = 0; i< numbers.length; i+= 1)
{
if (numbers[i] > 0)
{
for(int j = 0; j<total; j+=1)
{
nums[j] = numbers[i];
}
}
}
return nums;
}
}
You do not need the inner for. Just use index j to keep track of last place you filled the num array.
public class Example1 {
public static int[] getPositiveNumbes(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i +=1)
{
if (numbers[i] > 0)
{
total += 1;
}
}
int[] nums = new int[total];
int j = 0;
for ( int i = 0; i < numbers.length; i+= 1)
{
if (numbers[i] > 0)
{
num[j] = number[i];
j++;
}
}
return nums;
}

min n-m so that whole array will be sorted

I was asked the below question in an interview:
Given an array of integers, write a method to find indices m and n such that
if you sorted elements m through n, the entire array would be sorted. Minimize
n-m. i.e. find smallest sequence.
find my answer below and please do comment on the solution. Thanks!!!
At last I have got a solution to the problem, please feel free to comment.
Lets take an example:
int a[] = {1,3,4,6,10,6,16,12,13,15,16,19,20,22,25}
Now if i will put this in to the graph (X-coordinate -> array index and Y-coordinate -> array's value) then the graph will look like as below:
Now if we see the graph there are two places where dip happens one is after 10 and another after 16. Now in the zig zag portion if we see the min value is 6 and max val is 16. So the portion which we should sort to make the whole array sorted is between (6,16). Please refer to the below image:
Now we can easily divide the array in to three part. And middle part the one which we want to sort so that the whole array will be sorted. Please provide your valuable inputs. I tried to explain to my label best, please let me know if i want to explain more. Waiting for valuable inputs.
The below code implements the above logic:
public void getMN(int[] a)
{
int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE;
for(int i=1; i<a.length; i++)
{
if(a[i]<a[i-1])
{
if(a[i-1] > max)
{
max = a[i-1];
}
if(a[i] < min)
{
min = a[i];
}
}
}
if(max == Integer.MIN_VALUE){System.out.println("Array already sorted!!!");}
int m =-1, n =-1;
for(int i=0; i<a.length; i++)
{
if(a[i]<=min)
{
m++;
}
else
{
m++;
break;
}
}
for(int i=a.length-1; i>=0; i--)
{
if(a[i]>=max)
{
n++;
}
else
{
n++;
break;
}
}
System.out.println(m +" : "+(a.length-1-n));
System.out.println(min +" : "+max);
}
It's easier to find the max value starting from the end of array:
public void FindMinSequenceToSort(int[] arr)
{
if(arr == null || arr.length == 0) return;
int m = 0, min = findMinVal(arr);
int n = arr.length - 1, max = findMaxVal(arr);
while(arr[m] < min)
{
m ++;
}
while(arr[n] > max)
{
n --;
}
System.out.println(m);
System.out.println(n);
}
private int findMinVal(int[] arr)
{
int min = Integer.MAX_VALUE;
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < arr[i-1] && arr[i] < min)
{
min = arr[i];
}
}
return min;
}
private int findMaxVal(int[] arr)
{
int max = Integer.MIN_VALUE;
for(int i = arr.length - 2; i >= 0; i--)
{
if(arr[i] >= arr[i+1] && arr[i] > max)
{
max = arr[i];
}
}
return max;
}
Actually, I came up with something like that:
public static void sortMthroughN(int[] a)
{
int m = -1;
int n = -1;
int k = -1;
int l = -1;
int biggest;
int smallest;
// Loop through to find the start of the unsorted array.
for(int i = 0; i < a.length-1; i++)
if(a[i] > a[i+1]) {
m = i;
break;
}
// Loop back through to find the end of the unsorted array.
for(int i = a.length-2; i > 0; i--)
if(a[i] > a[i+1]) {
n = i;
break;
}
biggest = smallest = a[m];
// Find the biggest and the smallest integers in the unsorted array.
for(int i = m+1; i < n+1; i++) {
if(a[i] < smallest)
smallest = a[i];
if(a[i] > biggest)
biggest = a[i];
}
// Now, let's find the right places of the biggest and smallest integers.
for(int i = n; i < a.length-1; i++)
if(a[i+1] >= biggest) {
k = i+1; //1
break;
}
for(int i = m; i > 0; i--)
if(a[i-1] <= smallest) {
l = i-1; //2
break;
}
// After finding the right places of the biggest and the smallest integers
// in the unsorted array, these indices is going to be the m and n.
System.out.println("Start indice: " + l);
System.out.println("End indice: " + k);
}
But, I see that results are not the same with your solution #Trying, did i misunderstand the question? By the way, at the and of your code, it prints
4 : 9
6 : 16
What are these? Which ones are indices?
Thanks.
EDIT: by adding place marked as 1 this:
if(a[i+1] == biggest) {
k = i;
break;
}
and 2:
if(a[i+1] == smallest) {
l = i;
break;
}
it is better.
Actually, you can have two pointers and the last pointer moves backward to check start index of the shortest unsorted sequence. It's kind of O(N2) but it is more cleaner.
public static int[] findMinUnsortedSequence(int[] array) {
int firstStartIndex = 0;
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[j] <= array[i]) {
startIndex = j + 1;
} else {
endIndex = i;
if (firstStartIndex == 0) {
firstStartIndex = startIndex;
}
}
}
}
return new int[]{firstStartIndex, endIndex};
}

Code is printing out largest subscript of the array when it should be printing maximum and minimum

I'm trying to print the largest and smallest values on an array, as well as their respective subscripts. I'm running into a problem where my code, though printing the highest and lowest values of the array, is returning the largest subscript (regardless of value) for both maximum and minimum arrays. The problem lies somewhere in the for loops, below.
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
int indexMax = 0;
int indexMin = 0;
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max < arrayOfNumbers[i])
max = arrayOfNumbers[i];
indexMax = i;
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min > arrayOfNumbers[i])
min = arrayOfNumbers[i];
indexMin = i;
This should work:
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
int indexMax = 0;
int indexMin = 0;
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max < arrayOfNumbers[i]) {
max = arrayOfNumbers[i];
indexMax = i;
}
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min > arrayOfNumbers[i]) {
min = arrayOfNumbers[i];
indexMin = i;
}
}
You forgot to put both lines after the ifs into braces. Each time the code inside the loops executed, the current index had been written into both indexMax and indexMin, and that's why after the loops finished, they contained the "largest subscript".

Categories

Resources