1、冒泡算法
例如:从小到大排序
比较相邻两个元素,若前一个元素大于后一个元素,则位置互换。
如果前一个元素不大于后一个元素,则后一个元素与下一个元素比较。
public class bubleSort {
public static void main(String[] args) {
int[] arr = {2021,10,19,13,59,11,22,33};
int[] sort = bubbleSort(arr);
for (int k = 0; k < sort.length; k++) {
System.out.print(sort[k]+ " ");
}
}
public static int[] bubbleSort(int[] sourceArray){
//对arr进行拷贝,不改变参数内容
int[] arr = Arrays.copyOf(sourceArray,sourceArray.length);
for (int i = 0; i < arr.length-1; i++) { //进行N-1轮排序
for (int j = 0;j< arr.length-i-1; j++){
if (arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
}
冒泡排序的优化
在未排序的序列中找到最小(大)元素,存放到序列的起始位置。
再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
public class bubleSort {
public static void main(String[] args) {
int[] arr = {2021,10,19,13,59,11,22,33};
int[] sort = bubbleSort(arr);
for (int k = 0; k < sort.length; k++) {
System.out.print(sort[k]+ " ");
}
}
public static int[] bubbleSort(int[] sourceArray){
//对arr进行拷贝,不改变参数内容
int[] arr = Arrays.copyOf(sourceArray,sourceArray.length);
for (int i = 0; i < arr.length-1; i++) { //进行N-1轮排序
boolean flag = true;//定义一个flag,如果falg为true则此次没有进行数据交换,退出循环
for (int j = 0;j< arr.length-i-1; j++){
if (arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = false;
}
}
if (flag)break;
}
return arr;
}
}
2、选择算法
public class selectionSort {
public static void main(String[] args) {
int[] arr = {1,3,5,7,9,2,4,6,8};
int[] sort = selectionSort(arr);
for (int k = 0; k < sort.length; k++) {
System.out.print(sort[k]+ " ");
}
}
public static int[] selectionSort(int[] sourceArray){
int[] arr = Arrays.copyOf(sourceArray,sourceArray.length);
int temp = 0;
for (int i = 0; i < arr.length-1; i++) { //进行N-1轮排序
int minIndex = i;
for (int j = i+1; j < arr.length; j++) {
if (arr[j]<arr[minIndex]){
minIndex = j; //记录找到的最小值下标
}
}
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
return arr;
}
}
3、插入排序