将网上查阅的资料和自己的练习做一个总结
参考资料:https://www.cnblogs.com/onepixel/articles/7674659.html
1.直接插入排序:平均、最好、最坏时间复杂度O(n²) 空间复杂度O(1) 稳定
public static void insertSort1(int[] arr){
for(int i=0; i<arr.length-1; i++){
for(int j=i+1; j>0; j--){
if(arr[j]<arr[j-1]){
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
针对上面的这个排序算法改进:首先上面的这个每次替换都要定义一个temp赋值需要插入的数,这样会造成不必要的浪费:
所以我们可以吧所有的大于需要插入的数先保存,然后进行比较,然后将最后的正确位置空出来。吧之前保存的需要插入的数放到正确位置上;
public static int[] sort2(int[] ins){
for(int i=1; i<ins.length; i++){
int temp = ins[i];//保存每次需要插入的那个数
int j;
for(j=i; j>0&&ins[j-1]>temp; j--){//这个较上面有一定的优化
ins[j] = ins[j-1];//吧大于需要插入的数往后移动。最后不大于temp的数就空出来j
}
ins[j] = temp;//将需要插入的数放入这个位置
}
return ins;
}
2.希尔排序
对于大规模的数组,插入排序很慢,因为它只能交换相邻的元素,每次只能将逆序数量减少 1。希尔排序的出现就是为了解决插入排序的这种局限性,它通过交换不相邻的元素,每次可以将逆序数量减少大于 1。
希尔排序使用插入排序对间隔 h 的序列进行排序。通过不断减小 h,最后令 h=1,就可以使得整个数组是有序的。
public class Shell<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
int h = 1;
while (h < N / 3) {
h = 3 * h + 1; // 1, 4, 13, 40, ...
}
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(nums[j], nums[j - h]); j -= h) {
swap(nums, j, j - h);
}
}
h = h / 3;
}
}
}
3.选择排序(伪)待优化
public static void main(String[] args) {
int a[]= {3,6,9,5,0,1,2,4,7,8};
SelectionSort(a);
}
private static void SelectionSort(int[] a) {
int temp=0;
//两层循环排序
for(int j=0;j<a.length-1;j++)
for(int i=j;i<a.length-1;i++) {
if(a[j]>a[i+1]) {
//change
temp=a[j];
a[j]=a[i+1];
a[i+1]=temp;
}
}
//输出
System.out.println(Arrays.toString(a));
}
3.选择排序(真):时间复杂度O(n²)
每一轮比较记录最小数的下标,每轮结束后将下标对应的元素与第一个元素交换,比起伪选择排序省去了无意义的交换
private static void selectionSort(int[] a) {
int temp=0;
int minIndex=0;
//两层循环排序
for(int j=0;j<a.length-1;j++) {
minIndex=j;
for(int i=j;i<a.length-1;i++) {
if(a[minIndex]>a[i+1]) {
//change index
minIndex=i+1;
}
}
temp=a[minIndex];
a[minIndex]=a[j];
a[j]=temp;
}
//输出
System.out.println(Arrays.toString(a));
}
4.堆排序
5.冒泡排序:时间复杂度O(n²)
private static void bubbleSort(int[] a) {
int temp=0;
//两层循环排序
for(int j=0;j<a.length-1;j++)
for(int i=0;i<a.length-1-j;i++) {
if(a[i]>a[i+1]) {
//change
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
//输出
System.out.println(Arrays.toString(a));
}
6.快速排序
7.归并排序
8.基数排序