date: 2024-02-28
title: Sort
author:
- AllenYGY
status: DONE
tags:
- NOTE
- Sort
- Algorithm
created: 2023-12-31
updated: 2024-04-09T11:28
publish: TrueSort Algorithm
稳定排序:排序前后两个相等的数相对位置不变,则算法稳定
Bubble sort, Insertion sort, Merge sort
非稳定排序:排序前后两个相等的数相对位置发生了变化,则算法不稳定
Quick sort, Heap sort
Default order from smallest to largest
public static void sort(int nums[]){
Bubble(nums, nums.length-1);
}
//* 优化 每次循环的最后一次交换后 该下标往右都不会再发生交换 */
public static void Bubble(int nums[],int j){
if(j==0) return ;
int x=0;
for(int i=0;i<j;i++){
if(nums[i]>nums[i+1]) {
int temp=nums[i];
nums[i]=nums[i+1];
nums[i+1]=temp;
x=i;
}
}
Bubble(nums, x);
}
遍历第一个元素到数组最后一个元素
每遍历一个元素就比较已经排好序的部分,倒序遍历回去知道找到可以插入的位置
Example:
public static void insertionSort(int A[]){
for(int p=1;i<A.length;p++){
int key=A[p]; int i=p-1;
while(i>=0 && A[i]>key){
A[i+1]=A[i]; //挪位置
i=i-1;
}
A[i+1]=key;
}
}
不断缩小排序范围
public static void insertionSort(int A[]){
Insertion(A, 1);
}
public static void insertionSort(int A[],int p){
if(p==A.length) return;
int key=A[p]; int i=p-1;
while(i>=0 && key<A[i]){
A[i+1]=A[i];
i--;
}
A[i+1]=key;
Insertion(A, p+1);
}
Use the first element as a pivot
Choose the pivot randomly
Use the median of the array 中位数
The median is the middle element if the array is sorted.
We will use the median of three
Compare just three elements: the left-most, right-most, and center
Swap these elements if necessary so that
The priority queue is a data structure that allows at least two operations
Heaps are “almost perfect binary trees”
Given a binary heap of node number n and height h
Insert in
Locate the current minimum in
Delete the current minimum in
Note:
节点A:
父节点: