先决条件:插入排序,快速排序,选择排序
在本文中,实现了一种结合了快速排序和插入排序的混合算法。顾名思义,混合算法结合了多种算法。
为什么使用混合算法:
如果输入的大小很大,则快速排序算法会非常有效。但是,在数组较小的情况下,插入排序比快速排序更有效,因为与快速排序相比,比较和交换的次数更少。因此,我们将两种算法结合使用两种方法进行有效排序。
注意: Selectionsort算法也可以与quicksort结合使用。尽管时间复杂度为O(N 2 ),但是这些算法在这种情况下被证明是有效的,因为仅当数组的大小小于阈值时才使用这些算法(本文为10 )。
空运行算法:
Let arr[] = {24, 97, 40, 67, 88, 85, 15, 66, 53, 44, 26, 48, 16, 52, 45, 23, 90, 18, 49, 80}
方法:想法是使用递归并连续查找数组的大小。如果大小大于阈值(10),则将对数组的该部分调用quicksort函数。否则,称为插入排序。
下面是混合算法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to perform the insertion sort
void insertion_sort(int arr[], int low, int n)
{
for(int i=low+1;ilow && arr[j-1]>val)
{
arr[j]= arr[j-1] ;
j-= 1;
}
arr[j]= val ;
}
}
//The following two functions are used
// to perform quicksort on the array.
// Partition function for quicksort
int partition(int arr[], int low, int high)
{
int pivot = arr[high] ;
int i ,j;
i = low;
j = low;
for (int i = low; i < high; i++)
{
if(arr[i] Quick + Insertion sort
void hybrid_quick_sort(int arr[], int low, int high)
{
while (low < high)
{
// If the size of the array is less
// than threshold apply insertion sort
// and stop recursion
if (high-low + 1 < 10)
{
insertion_sort(arr, low, high);
break;
}
else
{
int pivot = partition(arr, low, high) ;
// Optimised quicksort which works on
// the smaller arrays first
// If the left side of the pivot
// is less than right, sort left part
// and move to the right part of the array
if (pivot-low
Python3
# Python implementation of the above approach
# Function to perform the insertion sort
def insertion_sort(arr, low, n):
for i in range(low + 1, n + 1):
val = arr[i]
j = i
while j>low and arr[j-1]>val:
arr[j]= arr[j-1]
j-= 1
arr[j]= val
# The following two functions are used
# to perform quicksort on the array.
# Partition function for quicksort
def partition(arr, low, high):
pivot = arr[high]
i = j = low
for i in range(low, high):
if arr[i] Quick + Insertion sort
def hybrid_quick_sort(arr, low, high):
while low
输出:
[15, 16, 18, 23, 23, 24, 26, 40, 44, 45, 48, 49, 52, 53, 66, 67, 80, 85, 88, 90, 97]