排序(Sort)
二、冒泡排序和简单选择排序
1.冒泡排序
代码如下(示例):
package Sort.Buttonsort;
import java.text.SimpleDateFormat;
import java.util.Date;
/*规则:
1、一共需要进行数组大小-1次的循环
2、每一次排序的次数在逐渐减小
3、如果我们发现在某趟排序中,没有发生一次交换,可以提前结束冒泡排序*/
public class BubbleSort {
public static void main(String[] args) {
int[] array = {
3,9,-1,10,2};
int[] array1 = new int[80000];
for (int i = 0; i < 80000; i++) {
array1[i]=(int)(Math.random()*80000);
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(new Date()));
//System.out.println("排序前的数组为:"+ Arrays.toString(array1));
Bubblesort(array1);
System.out.println(simpleDateFormat.format(new Date()));
//System.out.println("排序后的数组为:"+Arrays.toString(array1));
}
//写一个静态方法直接调用冒泡排序
public static void Bubblesort(int[] array) {
int temp = 0;
boolean flag = false;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
flag = true;
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
if (flag== false){
break;
}else {
flag = false;
}
}
}
}
2.简单选择排序
代码如下(示例):
package Sort.SelectSort;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class SelectSort {
public static void main(String[] args) {
int[] array = {
101,34,119,1};
int[] array1 = new int[80000];
for (int i = 0; i < 80000; i++) {
array1[i]=(int)(Math.random()*80000);
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(simpleDateFormat.format(new Date()));
Selectsort(array1);
System.out.println(simpleDateFormat.format(new Date()));
System.out.println(Arrays.toString(array1));
}
public static void Selectsort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int num = i;
//找到最小的数
for (int j = i + 1; j < array.length; j++) {
if (min > array[j]) {
min = array[j];
num = j;
}
}
//如果不是原来的num,就交换
if (num!=i){
array[num] = array[i];
array[i] = min;
}
}
}
}
总结
由简到繁!
分步骤来写就行了。