JAVA programming (08) ----- sorting of array primary applications
Array primary application, create an array, compare large and small arrays, and arrange them in sequence
Package com. lovo; /*** create an array with 10 random numbers of less than 100. sort by bubble. Simple selection method ** @ author Abe **/public class Test04 {public static void main (String [] args) {int [] f = new int [10]; for (int I = 0; I <f. length; I ++) {// create 10 random numbers f [I] = (int) (Math. random () * 100 + 1); System. out. print (f [I] + "");} // Bubble Method (comparison of adjacent two numbers) boolean swapped = true; // (optimization 1 ): the sequence ends quickly when it is close to the goal. the method is: determine whether an exchange has occurred // compare the previous number with the next one. If the previous one is large, it is the switching position. After the end of the next round, it is the largest to the last. The number is not in the judgment of the // N number, two adjacent comparison, only use the comparison (N-1) times. // I = 1 start to I <f. length is N-1for (int I = 1; swapped & I <f. length; I ++) {swapped = false; // (optimization 1) set clearing at the beginning of each round // j = 1 here, unlike the above I, j [1] is already the second number of arrays. For (int j = 1; j <f. length-(I-1); j ++) {// The first round of N-1, after that, if (f [j] <f [j-1]) {swapped = true; // if (optimization 1) has an exchange, if there is no switch, it is arranged in ascending order. Stop the program f [j] = f [j] ^ f [j-1]. // forced f [j] and f [J-1] exchange method f [j-1] = f [j] ^ f [j-1]; f [j] = f [j] ^ f [j-1] ;}} System. out. print ("\ n"); for (int I = 0; I <f. length; I ++) {System. out. print (f [I] + "");} System. out. print ("\ n"); // simple sorting method (compare the first number with the next number) for (int I = 0; I <f. length; I ++) {f [I] = (int) (Math. random () * 100 + 1); System. out. print (f [I] + "");} // compare the first number with all the following, and select the largest number and the first number for exchange, n-1 wheel for (int I = 0; I <f. length-1; I ++) {int max = I; // pay the location where the maximum value is found to max, then the number at the beginning is fixed, and the next round starts to compare for (int j = I + 1; j <f. length; j ++) {if (f [j]> f [max]) {max = j ;}} if (I! = Max) {// The biggest problem with the Force update method is that. If the same number (not two numbers with equal values) is used, the value of f [max] = f [max] ^ f [I] is changed to 0. f [I] = f [max] ^ f [I]; f [max] = f [max] ^ f [I] ;}} System. out. print ("\ n"); for (int I = 0; I <f. length; I ++) {System. out. print (f [I] + "");}}}