排序算法整理——坑+后期的数据结构部分
冒泡排序
public static void bubble() {
int[] arr = {12,-2,2,4,90,5,10,-5,-8,9};
int temp = 0;
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-1-i; j++) {
if (arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
public static void bubble1() {
int[] is = {12,-2,2,4,90,5,10,-5,-8,9};
for (int i = 0; i < is.length-1; i++) {
for (int j = is.length-1; j > i; j--) {
if (is[j]<is[j-1]) {
int temp = is[j];
is[j] = is[j-1];
is[j-1] = temp;
}
}
}
System.out.println(Arrays.toString(is));
}
}
选择排序
public static void selectSort() {
int[] arr = {12,-2,2,4,90,5,10,-5,-8,9};
for (int i = 0; i < arr.length-1; i++) {
int minIndex = i;
for (int j = i; j < arr.length; j++) {
if (arr[minIndex]>arr[j]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
System.out.println(Arrays.toString(arr));
}
public static void selectSort1() {
int[] is = {12,-2,2,4,90,5,10,-5,-8,9};
for (int i = 0; i < is.length-1; i++) {
int minIndex = i;
for (int j = is.length-1; j > i; j--) {
if(is[j]<is[minIndex]){
minIndex = j;
}
}
int temp = is[minIndex];
is[minIndex]= is[i];
is[i] = temp;
}
System.out.println(Arrays.toString(is));
}
插入排序
public static void InsertSort(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length-1; i++) {
for (int j = i+1; j >0 ;j--) {
if (arr[j]<arr[j-1]) {
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}