简记,来源于牛客网一道题目的解析:https://www.nowcoder.com/profile/829529129/test/25668958/111954#summary
选择排序,i不动,j=i+1,j自增,比较a[i]和a[j];冒泡排序:i不动,i=j,j自增,比较a[j]和a[j+1]
搜索笔试速记
//冒泡
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(R[j]<R[j+1])
{
swap(&R[j],&R[j+1]);
}
}
}
//冒泡优化
for(i=0;i<n-1;i++)
{
isSorted = 0;
for(j=0;j<n-1-i;j++)
{
if(R[j]>R[j+1])
{
swap(&R[j],R[j+1]);
isSorted=1;
}
}
if(isSorted==0)
{
break;//最优情况
}
}
//快速排序
void QuickSort(SeqList R, int m, int n)
{
int pivot;
if(m < n)
{
pivot = Partition(R, m, n);
QuickSort(R, m, pivot-1);
QuickSort(R, pivot+1, n);
}
}
int Partition(SeqList R, int m, int n)
{
int mid = m + (m-n)/2;
if(R[m]<R[n]) swap(&R[m], &R[n]);
if(R[m]>R[mid]) swap(&R[m], R[mid]);
if(R[n]<R[mid]) swap(&R[n], &R[mid]);
swap(&R[m], &R[mid]);
int pivot = R[m];
int i = m, j = n;
while(i<j)
{
while(i<j&&pivot<=R[j])
j--;
if(i<j) R[i++] = R[j];
while(i<j&&pivot>=R[i])
i++;
if(i<j) R[j--] = R[i];
}
return i;
}
//选择排序
for(i=0;i<n-1;i++)
{
minIndex = i;
for(j=i+1;j<n;j++)
{
if(R[minIndex]>R[j])
{
minIndex = j;
}
}
if(minIndex != i)
{
swap(&R[minIndex], &R[i]);
}
}
//希尔排序
//https://blog.csdn.net/double_sweet1/article/details/101476886
//https://baike.baidu.com/item/%E5%B8%8C%E5%B0%94%E6%8E%92%E5%BA%8F/3229428?fr=aladdin#2
int n=sizeof(array), gap;
for(gap=n/2;gap>0;gap/=2)
{
for(int i=gap;i<n;i++)
{
insertI(array,gap,i);
}
}
void insertI(int array[],int gap, int i)
{
int inserted=array[i],j=i-gap;
while(j>=0&&array[j]>inserted)
{
array[j+gap]=array[j];
j-=gap;
}
if(j!=i-gap)
{
array[j+gap]=inserted;
}
}
搜索
二叉搜索,复杂度最差
def BinarySort(lyst, target):
left = 0
right = len(target) - 1
while left < right:
mid = (left + right) // 2
if(lyst[mid] == target):
return mid
elif target < lyst[mid]:
right = mid - 1
else:
left = mid + 1
return -1
排序
O(n)
Bucket Sort
def bucket_sort(a):
buckets = [0] * ((max(a) - min(a)) + 1) # 初始化桶元素为0
for i in range(len(a)):
buckets[a[i] - min(a)] += 1 # 遍历数组a,在桶的相应位置累加值
b = []
for i in range(len(buckets)):
if buckets[i] != 0:
b += [i + min(a)] * buckets[i]
return b
l = [2,4,6,5,3,1]
bucket_sort(l)
O(n^2)
Bubble Sort:平均和最差O(n^2),最优列表是已经排序好的情况下O(n)
def bubbleSort(lyst):
n = len(lyst)
while n > 1:
swaped = False
i = 1
while i < n:
if lyst[i] < lyst[i - 1]:
lyst[i], lyst[i - 1] = lyst[i - 1], lyst[i]
swaped = True
i += 1
if(not swaped):return
n -= 1
InsertSort,列表排序好时最好是O(n),其他情况是O(n^2)
def insertionSort(lyst):
i = 1
while i <len(lyst):
itemToInsert = lyst[i]
j = i - 1
while j >= 0:
if lyst[j] > itemToInsert:
lyst[j + 1] = lyst[j]
j -= 1
else:
break
lyst[j + 1] = itemToInsert
i += 1
SelectionSort,从小到大排序,冒泡法是先找到最大的数,选择排序先找到最小的数
def selectionSort(lyst):
i = 0
while i < len(lyst) - 1:
minIndex = i
j = i + 1
while j <len(lyst):
if lyst[j] < lyst[minIndex]:
minIndex = j
j += 1
if minIndex != 1:
lyst[minIndex], lyst[i] = lyst[i], lyst[minIndex]
i += 1