一、快排
c++
void quick_sort(int q[], int l, int r)
{
if (l >= r) return;
int i = l - 1, j = r + 1, x = q[l + r >> 1];
while (i < j)
{
do i ++ ; while (q[i] < x);
do j -- ; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}
quick_sort(q, l, j), quick_sort(q, j + 1, r);
}
作者:yxc
链接:https://www.acwing.com/blog/content/277/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
python
def quick_sort(q,l,r):
# 判断特殊情况
if l>=r:
return
# 定边界
i = l-1
j = r+1
x =q[l+r>>1]
# 分左右
while(i<j):
i += 1
while(q[i]<x):
i += 1
j -= 1
while(q[j]>x):
j -= 1
if i<j:
q[i],q[j]=q[j],q[i]
quick_sort(q,l,j)
quick_sort(q,j+1,r)
785快排
def quick_sort(q,l,r):
# 判断特殊情况
if l>=r:
return
# 定边界
i = l-1
j = r+1
x =q[l+r>>1]
# 分左右
while(i<j):
i += 1
while(q[i]<x):
i += 1
j -= 1
while(q[j]>x):
j -= 1
if i<j:
q[i],q[j]=q[j],q[i]
quick_sort(q,l,j)
quick_sort(q,j+1,r)
n = int(input())
nums = list(map(int,input().split()))
quick_sort(nums,0,n-1)
print(" ".join(map(str,nums)))
786快选
def quick_sort(q,l,r,k):
if l==r:
return q[l]
i = l-1
j = r+1
x = q[l+r>>1]
while(i<j):
i += 1
while(q[i]<x):
i += 1
j -= 1
while(q[j]>x):
j -= 1
if(i<j):
q[i],q[j]=q[j],q[i]
sl = j-l+1
if k<=sl:
# 此处要return回去,不然最开始的函数得不到最里层函数的值
return quick_sort(q,l,j,k)
else:
return quick_sort(q,j+1,r,k-sl)
a = list(map(int,input().split()))
n,k = a[0],a[1]
nums = list(map(int,input().split()))
b = quick_sort(nums,0,n-1,k)
print(b)
二、归并排序
y总的
void merge_sort(int q[], int l, int r)
{
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
if (q[i] <= q[j]) tmp[k ++ ] = q[i ++ ];
else tmp[k ++ ] = q[j ++ ];
while (i <= mid) tmp[k ++ ] = q[i ++ ];
while (j <= r) tmp[k ++ ] = q[j ++ ];
for (i = l, j = 0; i <= r; i ++, j ++ ) q[i] = tmp[j];
}
作者:yxc
链接:https://www.acwing.com/blog/content/277/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
python
注意:# 在递归的时候不是赋值q的所有,而是其处理的坐标为l到r的部分
q[l:r+1] = tmp[:]
def merge_sort(q,l,r):
if l>=r:
return
mid = l+r>>1
merge_sort(q,l,mid)
merge_sort(q,mid+1,r)
tmp,i,j = [],l,mid+1
while i <= mid and j<=r:
if q[i]<=q[j]:
tmp.append(q[i])
i += 1
else:
tmp.append(q[j])
j += 1
if i<=mid:
tmp += q[i:mid+1]
if j<=r:
tmp += q[j:r+1]
# 在递归的时候不是赋值q的所有,而是其处理的坐标为l到r的部分
q[l:r+1] = tmp[:]
787
def merge_sort(q,l,r):
if l>=r:
return
mid = l+r>>1
merge_sort(q,l,mid)
merge_sort(q,mid+1,r)
tmp,i,j = [],l,mid+1
while i <= mid and j<=r:
if q[i]<=q[j]:
tmp.append(q[i])
i += 1
else:
tmp.append(q[j])
j += 1
if i<=mid:
tmp += q[i:mid+1]
if j<=r:
tmp += q[j:r+1]
# 在递归的时候不是赋值q的所有,而是其处理的坐标为l到r的部分
q[l:r+1] = tmp[:]
n = int(input())
nums = list(map(int,input().split()))
merge_sort(nums,0,n-1)
print(" ".join(map(str,nums)))