老分不清直接插入和简单选择,记住一个口诀:直接插入不直接,简单选择真简单
def partition(arr,low,high):
i = ( low-1 ) # 最小元素索引
pivot = arr[high]
for j in range(low , high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
# arr[] --> 排序数组
# low --> 起始索引
# high --> 结束索引
# 快速排序函数
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr,0,n-1)
print ("排序后的数组:")
for i in range(n):
print ("%d" %arr[i]),
public static void sort(int[] a) {
//只能用于判断趟数,省趟数,不省次数
boolean flag = true;
for (int i = 0; i < a.length - 1; i++) {
//排序n - 1趟
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j+1]) {
swag(a,j,j+1);
flag = false;
}
}
if (flag) {
break;
} else {
//不重置只要交换过就没用了
flag = true;
}
}
}


搬运自:https://blog.csdn.net/weixin_42264992/article/details/124968645
大顶堆:
def topHeap(list,size):
#i节点的子节点为2i+1,2i+2
for i in range(size-1,-1,-1):
if 2*i+1<size: #左孩子存在
if list[2*i+1]>list[i]:
list[2*i+1],list[i]=list[i], list[2*i+1]
if 2*i+2<size: #右孩子存在
if list[2*i+2]>list[i]:
list[2*i+2],list[i]=list[i], list[2*i+2]
list=[11,2,3,4,12,18,16]
for i in range(len(list),0,-1):
topHeap(list,i)
list[0],list[i-1]=list[i-1],list[0] #每轮交换栈顶元素至相应位置
print(list)
小顶堆:
def topHeap(list,size): #i节点的子节点为2i+1,2i+2
for i in range(size-1,-1,-1):
if 2*i+1<size: #左孩子存在
if list[2*i+1]<list[i]:
list[2*i+1],list[i]=list[i], list[2*i+1]
if 2*i+2<size: #右孩子存在
if list[2*i+2]<list[i]:
list[2*i+2],list[i]=list[i], list[2*i+2]
list=[11,2,3,4,12,18,16]
for i in range(len(list),0,-1):
topHeap(list,i)
list[0],list[i-1]=list[i-1],list[0] #每轮交换栈顶元素至相应位置
print(list)
参考链接:https://blog.csdn.net/a574780196/article/details/122646309

#include
#include
#include
int main()
{
using namespace std;
using VI = vector<int>;
vector<VI> src = { {1, 2, 3}, {2, 4, 6}, {3, 5, 8} };
priority_queue<VI, vector<VI>, greater<VI>> pq;
VI vc;
//1.先将每路的最小值(第一列元素)放入堆中, 以获得全局的最小值
for(int i = 0; i < src.size(); ++i)
{
vc = {src[i][0], i, 0}; //值, 纵坐标, 横坐标
pq.emplace(vc);
}
VI ans;
while( !pq.empty() )
{
vc = pq.top(); //弹出堆顶元素
pq.pop();
ans.emplace_back(vc[0]);
//将堆顶元素所在数组的下一个元素放入堆中
if(vc[2] < src[vc[1]].size() - 1) {
vc = {src[ vc[1] ][ vc[2] + 1 ], vc[1], vc[2] + 1};
pq.emplace(vc);
}
}
for(auto &x : ans)
{
cout << x << " ";
}
return 0;
}
priority_queue<int,vector<int> , greater<>> pq;//这是对的