冒泡法
就是头和下面的每一个数进行比较,如果头比后边大,就交换。
package chapter5;
import java.util.Random;
public class ArrayFirst {
public static void main(String[] args) {
int[] myArray;
myArray = new int[9];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = new Random().nextInt(10) + 1;
}
System.out.println("the number system generate are");
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
System.out.println();
System.out.println("now we will sort it as 1~9:");
for (int i = 0; i < myArray.length; i++) {
//int k;
int tmp;
//k = i;
for (int j = i + 1; j < myArray.length; j++) {
if (myArray[i] > myArray[j]) {
tmp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = tmp;
}
}
}
System.out.println("now the result is: ");
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
}
}
冒泡改进法:
使用K,先假设K就是i,然后让k和后边的逐一比较,如果发现比后边大,先不交换,让k = j,记住位置。
等 j 循环完一圈后,交换a[i] 和a[k] 的位置。
package chapter5;
import java.util.Random;
public class ArrayFirst {
public static void main(String[] args) {
int[] myArray;
myArray = new int[9];
for (int i = 0; i < myArray.length; i++) {
myArray[i] = new Random().nextInt(10) + 1;
}
System.out.println("the number system generate are");
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
System.out.println();
System.out.println("now we will sort it as 1~9:");
for (int i = 0; i < myArray.length; i++) {
int k,tmp;
k = i;
for (int j = k + 1; j < myArray.length; j++) {
if (myArray[k] > myArray[j]) {
k = j;
}
}
if (i != k) {
tmp = myArray[i];
myArray[i] = myArray[k];
myArray[k] = tmp;
}
}
System.out.println("now the result is: ");
for (int i = 0; i < myArray.length; i++) {
System.out.print(myArray[i] + " ");
}
}
}