Sunday, December 27, 2009

How Do You Find The Two Lowest Values In An Array? (Java Programming)?

The previous answer is mighty good!





I was just thinking you could sort the array from lowest to highest.


Then you would take the fron 2 values, add them, and INSERT the result into the array (insertion sort).





Each time you do this, the overall size of the array is reduced by 1.How Do You Find The Two Lowest Values In An Array? (Java Programming)?
I'd use a logical switch statement, nested in a while.





double swapDoub = 0.0;


double firstHighest = array[0];


double secondHighest = 0.0;





while (i %26lt; (array.length()-1))


switch (Double.compare(firstHighest,array[i+1])


{


{


case 0:


case 1:


// If first highest is greater than array element,


// compare to second


switch (Double.compare(secondHighest,array[i+1]鈥?br>

case 0:


case 1:


// If second highest is greater than array element, increment i


i++


break;


case -1:


// If second highest is less than array element,


// assign array element to second highest.


secondHighest = array[i+1]


i++


break;


break;


case -1:


// If first highest is less than array element, assign to first highest


swapDoub = firstHighest // Swap values.


firstHighest = array [i+1]


switch (Double.compare(swapDoub,secondHighest){


case 0:


case 1:


// If swapDoub %26gt; secondHighest, insert value


secondHighest = swapDoub


i++


break;


case -1:


// If swapDoub less than secondHighest, increment


i++


break;


break;


}


}





Once it kicks free of the loop, sum the two Highest, reinsert into a new array of array.length - 1 elements, repeat.How Do You Find The Two Lowest Values In An Array? (Java Programming)?
This can be done with looping and iteration.





Make 2 variables and a for loop,





create a sequential algorithms in the loop to replace the 2 variables whenever they encounter something that is lower than either of them, compare them to each other, then swap if necessary.
What exactly is the point of doing that? If you keep repeating it you end up with the sum of all the numbers in the array anyway, regardless of what order they are added in.





But for what it's worth, I like the second answer. There's no point writing a load of code from scratch when you can re-use commonly used code anyway, i.e insertion sort, and just writing a small bit yourself to deal with adding the too lowest numbers which is a very trivial task.
  • blonde highlight
  • oil offshore
  • printer ink
  • printer ink
  • No comments:

    Post a Comment