java - Sorting three integers -
java - Sorting three integers -
to start off, yes working on intro programming assignment, have spent day , night trying solve progress no success.
the exercise create method sorts 3 ints to the lowest degree greatest. not encouraged utilize arrays, @ point cant figure out how accomplish without help of array.
i started out trying figure out how "sort" 3 integers , came with:
public class sortinteger { public static void main(string[]args) { int = integer.parseint(args[0]); int b = integer.parseint(args[1]); int c = integer.parseint(args[2]); int n1, n2, n3 = 0; if (a < b && < c) { n1 = a; } else if (b < && b < c) { n1 = b; } else { n1 = c; } if (a > b && > c) { n3 = a; } else if (b > && b > c) { n3 = b; } else { n3 = c; } if (n1 < && < n3) { n2 = a; } else if (n1 < b && b < n3) { n2 = b; } else {n2 = c;} system.out.println( n1 + " " + n2 + " " + n3); } }
i sense cut down amount of if statements , simplify alot of lines in above code, want wait until succeed before start cleaning program. also, code works goal write static method. after getting far began attempts on converting static method , have come far:
public class sortinteger2 { public static int sort(int a, int b, int c) { int []s = new int [3]; if (a < b && < c) { s[0] = a; } else if (b < && b < c) { s[0] = b; } else {s[0] = c;} if (a > b && > c) { s[2] = a; } else if (b > && b > c) { s[2] = b; } else {s[2] = c;} if (s[0] < && < s[2]) { s[1] = a; } else if (s[0] < b && b < s[2]) { s[1] = b; } else {s[1] = c;} homecoming s[]; //i dont know how homecoming array, didnt work me } public static void main(string[]args) { int = integer.parseint(args[0]); int b = integer.parseint(args[1]); int c = integer.parseint(args[2]); int []s = new int [3]; s = sort(a,b,c); system.out.println(s[0] + " " + s[1] + " " + s[2]); } }
i know can homecoming single object, why chose utilize array store 3 integers , homecoming single object array. however, compiler still yells @ me when seek it. missing here? sense obvious isnt clicking when examine on , over. if steered in right direction, much appreciate it!
"i sense cut down amount of if statements , simplify alot of lines in above code,"
you can maintain using a, b, c instead of making new variables, , swap them based on comparisons, other that, there's not much reducing made.
"also, code works goal write static method."
why not this?
public static void sort(int a, int b, int c) { ... system.out.println( n1 + " " + n2 + " " + n3); } public static void main(string[] args) { sort(2, 5, 9); }
if you're still intent on using arrays, alter homecoming value of sort
int[]
. then, alter line return s[]
return s
, signifying you're returning array.
java arrays sorting
Comments
Post a Comment