Original article, if reproduced, please indicate the source: http://blog.csdn.net/yihui823/article/details/6833067
Bad code:
Int [] iarray = {12,122,123,124, 1,}; // sorts the iarray int Imin = 999999; int indexmin = 0; int itmp = 0; For (INT I = 0; I <iarray. length; I ++) {// find the smallest for (Int J = I; j <iarray. length; j ++) {If (Imin> iarray [J]) {Imin = iarray [J]; indexmin = J ;}} // put at the beginning itmp = iarray [I]; iarray [I] = iarray [indexmin]; iarray [indexmin] = itmp;} For (INT I = 0; I <iarray. length; I ++) {system. out. print (iarray [I] + ",");} system. out. println ();
First, there is a bug. The minimum value is initialized with 999999. If the number in the array is greater than 999999, the sorting will not proceed.
You can change 999999 to integer. max_value.
Second, you just sort an array and do not need to write it yourself. Arrays contains the sorting function. The program can be changed:
Int [] iarray = {12,122,123,124, 1,}; // sorts arrays by iarray. sort (iarray); For (INT I = 0; I <iarray. length; I ++) {system. out. print (iarray [I] + ",");} system. out. println ();
So what if we want to sort an object instead of an integer?
For example, we have a class:
public class Point {private int x;private int y;public Point(int x, int y) {this.x = x;this.y = y;}}
Now we need to sort an array of this class. Can I use the sorting function of the system. Of course.
First, our class must implement the interface: comparable. That is, this object must be comparable.
Second, we need to implement the function defined by this interface: compareto.
The modified class is as follows:
public class Point implements Comparable {private int x;private int y;public Point(int x, int y) {this.x = x;this.y = y;}private int getMix() {return (x << 8) + y;}@Overridepublic int compareTo(Object o) {Point other = (Point) o;return getMix() - other.getMix();}@Overridepublic String toString() {return "(" + x + "," + y + ")";}}
The sorting code is as follows:
// Randomly generate five objects: Random random = new random (); List <point> lst = new arraylist <point> (); For (INT I = 0; I <5; I ++) {lst. add (new point (random. nextint (100), random. nextint (100);} Point [] parray = lst. toarray (new point [lst. size ()]); // sorts the point array. sort (parray); For (INT I = 0; I <parray. length; I ++) {system. out. print (parray [I] + ",");} system. out. println ();
In the compareto function, the values of the objects to be compared are generally the values corresponding to the objects to be compared. If compareto returns a negative number, it indicates that the current object is smaller than the input parameter.