right now I have a project dealing with fractions. The fractions need to be sorted and the highest and lowest are dropped, and then the middle fractions are added together. I have created the array, and done the sort. I am stuck as to how to drop the highest and lowest. Any help is appreciated, thanks!
public class Tester {
public static void main(String[] args) {
double[] fractions = {(6/7),(2/4),(3/4),(3/18),(1/8),(10/20),(2/6)};
}
public static void selectionSort (int... arr)
{
int i = 0, j = 0, smallest = 0;
int temp = 0;
for (i = 0;i<arr.length - 1;i++)
{
smallest = i;
for (j = 1; j<arr.length - 1; j++)
{
if (arr[j]<arr[smallest])
smallest = j;
}
temp = arr[smallest];
arr[smallest] = arr[i];
arr[i] = temp;
}
//Drop highest and lowest here
}
}
First off you have to add decimal points to either the denominator or numerator in your array initialization to get an array that is not full of 0
's (That way you are not doing integer math). Or simply add a d
at the end of your integer math ( 6/7d
).
Next you can sort using Arrays.sort
(or continue using your custom sort method) and you can get a sub array using Arrays.copyOfRange
. This is very handy since you can give it a starting index and an ending index. Something like this should do the trick:
public static void main(String[] args) {
double[] fractions = {(6./7),(2./4),(3./4),(3./18),(1./8),(10./20),(2./6)}; //Add decimal points
Arrays.sort(fractions); //Sort your array
double[] removeLowestAndHighest = Arrays.copyOfRange(fractions, 1, fractions.length-1); //returns new array with first and last element removed.
}
我建议使用List,然后您可以简单地使用.remove(0)、. remove(size-1)
// Create a new array that is 2 smaller than the orriginal.
int[] newArr = new int[arr.length-2];
// Iterate through the old array, skipping the first and last elements.
for(int i = 0; i < newArr.length; i++)
{
newArr[i] = arr[i+1];
}
You could convert the array to a list to remove the min/max and then convert back to an array if necessary
You could use Arrays.asList(array) for the conversion
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
Collections has a min and a max method you can use on the list to determine what you need to remove
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.