一、冒泡排序BubbleSort
public class InsertSort {
public static void sort(long[] arr) {
long tmp = 0;
for(int i = 1; i < arr.length; i++) {
tmp = arr[i];
int j = i;
while(j > 0 && arr[j] >= tmp) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = tmp;
}
}
}
二、插入排序InsertSort
public class InsertSort {
public static void sort(long[] arr) {
long tmp = 0;
for(int i = 1; i < arr.length; i++) {
tmp = arr[i];
int j = i;
while(j > 0 && arr[j] >= tmp) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = tmp;
}
}
}
三、选择排序SelectionSort
public class SelectionSort {
public static void sort(long[] arr) {
int k = 0;
long tmp = 0;
for(int i = 0; i < arr.length - 1; i++) {
k = i;
for(int j = i; j < arr.length; j++) {
if(arr[j] < arr[k]) {
k = j;
}
}
tmp = arr[i];
arr[i] = arr[k];
arr[k] = tmp;
}
}
}
四、调用测试
public class TestSort {
public static void main(String[] args) {
long[] arr = new long[5];
arr[0] = 34;
arr[1] = 23;
arr[2] = 2;
arr[3] = 1;
arr[4] = -4;
System.out.print("[");
for(long num : arr) {
System.out.print(num + " ");
}
System.out.print("]");
System.out.println();
InsertSort.sort(arr);
System.out.print("[");
for(long num : arr) {
System.out.print(num + " ");
}
System.out.print("]");
System.out.println();
}
}
|