Article directory
1 Binary search
- Define two variables
left
andright
, representing the left and right boundaries of the array respectively. The initial values are respectively0
andlen - 1
, wherelen
is the length of the array. - Calculate the middle position of the array
mid
, the formula is , and determine whether(left + right) / 2
the element at that position in the array is equal to the target value .num[mid]
target
- If they are equal, the target value is found and returned
mid
as the result. - If they are not equal, compare
num[mid]
thetarget
size of the sum. Ifnum[mid] < target
, it means that the target value is in the right half of the array, so the left boundary is updated asmid + 1
; ifnum[mid] > target
, it means that the target value is in the left half of the array, so the right boundary is updated asmid - 1
. - Repeat steps 2 to 4 until the left boundary is greater than the right boundary. At this time, it means that the target value does not exist in the array, and -1 is returned as the result.
The advantage of the binary search algorithm is that the search speed is fast and the time complexity is O (logn) O(logn)O ( log n ) , where n is the length of the array . The disadvantage is that the array must be ordered, and it is not applicable to dynamically changing arrays.
int BinarySearch(int num[],int target,int len)
{
int left = 0, right = len - 1;
while(left <= right)
{
int mid = (left + right) / 2;
if(num[mid]==target)
{
return mid;
}
else if(num[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
2 Bubble sort
- Define a variable
i
that represents the position of the last element in the unsorted part of the array, with an initial value oflength - 1
, wherelength
is the length of the array. - Starting from the first element of the array, compare the two adjacent elements in sequence. If the former element is
num[j]
greater than the latter elementnum[j+1]
, swap their positions, so that the larger element can be moved backward. - Repeat step 2 until the last element in the unsorted part of the array is traversed. At this time, you can determine that the element is the largest element in the array and arrange it in the correct position.
- Decrement the variable
i
by one, indicating that the length of the unsorted part of the array is reduced by one element, and then return to step 2 to continue comparison and exchange. - Repeat steps 2 to 4 until the variable
i
is less than or equal to 1. At this time, all elements in the array have been sorted and the algorithm ends.
The advantage of the bubble sort algorithm is that it is simple and easy to understand and does not require additional space. The disadvantage is low efficiency and time complexity of O ( n 2 ) O(n^2)O ( n2 ), where n is the length of the array.
void BubbleSort(int num[],int length)
{
for(int i=length-1;i>1;i--)
{
for(int j=0;j<i;j++)
{
if(num[j] > num[j+1])
{
int tmp = num[j+1];
num[j+1] = num[j];
num[j] = tmp;
}
}
}
}
3 Heap sort
- Define a function
MaxHeap
whose function is to adjust a part of the elements in an array into a large root heap, that is, a binary tree in which the value of the parent node is greater than or equal to the value of the child node. There are three parameters of the function, which arenum
the array,start
the starting position of the adjustment,end
and the end position of the adjustment. - In the function
MaxHeap
, define two variablesdad
andson
, respectively representing the positions of the parent node and child node currently to be adjusted. The initial values are respectively andstart
(start * 2 + 1
because the array subscript starts from 0, so the left child node is the parent node multiplied by 2 plus 1 ). - Determine whether the child node is within the adjustment range. If so, continue to perform the following steps; if not, the adjustment has been completed and return.
- If there is a right child node and the value of the right child node is greater than the value of the left child node, update the child node to the right child node (i.e. select the larger child node).
- Compare the values of the parent node and the child node. If the value of the parent node is greater than or equal to the value of the child node, it means that the properties of the large root heap have been met and return; if not, the values of the parent node and child node are exchanged, and the parent node is updated to the original value. The child node is updated to the left child node of the original parent node (that is, the adjustment continues to the next level).
- Repeat steps 3 to 5 until adjustment is complete or return.
- Define a
HeapSort
function that performs heap sort on an array. There are two parameters of the function, which arenum
the array andlen
the length of the array. - Starting from the middle of the array and executing the function on each element
MaxHeap
in turn, the entire array can be adjusted into a large root heap (i.e. the first element is the largest element). - Starting from the last element of the array, perform the following steps in sequence:
- Swap the values of the first element and the current element so that the largest element is placed in the correct position.
- Performing a function on elements other than the current one
MaxHeap
resizes the remainder into a large root heap (i.e. the first element is the largest element of the remainder).
- Repeat step 9 until only the first element remains. At this time, all elements in the array have been sorted and the algorithm ends.
The advantage of the heap sort algorithm is high efficiency and time complexity of O (nlogn) O(nlogn)O ( n log n ) , where n is the length of the array . The disadvantage is that additional space is required to store the heap structure, and it is not suitable for situations with high stability requirements.
void MaxHeap(int num[],int start,int end)
{
int dad = start;
int son = dad * 2 + 1;
while(son <=end)
{
if((son+1<=end) && (num[son]<num[son+1]))
{
son++;
}
if(num[son]<num[dad])
{
return;
}
else
{
int tmp = num[dad];
num[dad] = num[son];
num[son] = tmp;
dad = son;
son = dad * 2 + 1;
}
}
}
void HeapSort(int num[],int len)
{
for(int i=len/2-1;i>=0;i--)
{
MaxHeap(num,i,len-1);
}
for(int i=len-1;i>0;i--)
{
int tmp = num[0];
num[0] = num[i];
num[i] = tmp;
MaxHeap(num,0,i-1);
}
}
4 Insertion sort
- Define a variable
i
to represent the position of the element currently to be inserted. The initial value is1
, indicating starting from the second element of the array. - Save the current element to be inserted
num[i]
in a temporary variabletmp
so it won't be overwritten. - Define a variable
j
that represents the position of the last element of the sorted part, with an initial value ofi - 1
. - Compare the size of the last element of the sorted part
num[j]
with the size of the element to be insertedtmp
. If the former is greater than the latter, move the former one backward, which is about tonum[j]
be assigned tonum[j+1]
, andj
subtract one; if not, it means that it is found. The position to insert, break out of the loop. - Assign the element to be inserted
tmp
to the found position, which is about totmp
be assigned tonum[j+1]
. - Add one to the variable
i
to indicate that the next element is to be inserted, and return to step 2 to continue comparison and movement. - Repeat steps 2 to 6 until the variable
i
is equal to the length of the array. At this time, all elements in the array have been sorted and the algorithm ends.
The advantage of the insertion sort algorithm is that it is simple and easy to understand, and it is more efficient for partially ordered arrays or small amounts of data. The disadvantage is low efficiency and time complexity of O ( n 2 ) O(n^2)O ( n2 ), where n is the length of the array.
void InsertSort(int num[],int length)
{
for(int i=1;i<length;i++)
{
int tmp = num[i];
int j = i - 1;
while((j>=0) && (num[j]>tmp))
{
num[j+1] = num[j];
j--;
}
num[j+1] = tmp;
}
}
5 Quick sort
- Define a
QuickSort
function that performs quick sorting on a portion of an array. There are three parameters of the function, which arenum
the array,start
the starting position of sorting,end
and the end position of sorting. - Determine whether sorting is required. If the starting position is greater than or equal to the ending position, it means the sorting has been done and return; if not, continue to perform the following steps.
- Define two variables
i
andj
, respectively representing the left boundary and right boundary of the current part to be divided. The initial values arestart
respectivelyend
. - Select the first element in the array
num[i]
as the base value and save it in a temporary variablebasenum
so that it is not overwritten. - Starting from the right boundary, search to the left for an element smaller than the base value. If found, assign it to the left boundary position; if not found, decrease the right boundary by one and continue searching.
- Starting from the left boundary, search to the right for an element greater than the base value. If found, assign it to the right boundary position; if not found, add one to the left boundary and continue searching.
- Repeat steps 5 and 6 until the left and right boundaries meet or intersect. At this time, a division has been completed, and the reference value is assigned to the location where they meet or intersect.
- The function is recursively executed for the part to the left of the reference value
QuickSort
, and the function is recursively executed for the part to the right of the reference valueQuickSort
. - Repeat steps 2 to 8 until all parts are sorted and the algorithm ends.
The advantage of the quick sort algorithm is high efficiency and time complexity of O (nlogn) O(nlogn)O ( n log n ) , where n is the length of the array . The disadvantage is that it is unstable and inefficient for extreme cases (such as the array is already sorted or reversed).
void QuickSort(int num[],int start,int end)
{
if(start >= end) return;
int i = start;
int j = end;
int basenum = num[i];
while(i<j)
{
//从右往左找小值
while((i<j) && (num[j]>=basenum))
{
j--;
}
if(i<j)
{
num[i] = num[j];
i++;
}
//从左往右找大值
while((i<j) && (num[i]<basenum))
{
i++;
}
if(i<j)
{
num[j] = num[i];
j--;
}
num[i] = basenum;
}
QuickSort(num,start,i-1);
QuickSort(num,i+1,end);
}
6 Select sort
- Define a variable
i
to represent the current position to be selected. The initial value is0
, which means starting from the first element of the array. - Define a variable
min
to represent the position of the current smallest element, with an initial value ofi
. - Starting from the current position, traverse each element in the array backwards. If an element smaller than the current smallest element is found, assign its position to, so that the smallest
min
element in the current range can be found. - Swap the current position and the value of the smallest element, which will be
num[min]
assigned tonum[i]
, and which willnum[i]
be assigned tonum[min]
, so that the smallest element is placed in the correct position. i
Add one to the variable to indicate that you want to select the next position, and go back to step 2 to continue selecting and exchanging.- Repeat steps 2 to 5 until the variable
i
is equal to the length of the array minus one. This means that all elements in the array have been sorted and the algorithm ends.
The advantage of the selection sort algorithm is that it is simple and easy to understand and does not require additional space. The disadvantage is low efficiency and time complexity of O ( n 2 ) O(n^2)O ( n2 ), where n is the length of the array.
void SelectSort(int num[],int length)
{
for(int i=0;i<length-1;i++)
{
int min = i;
for(int j=i;j<length;j++)
{
if(num[j]<num[min])
{
min = j;
}
}
int tmp = num[min];
num[min] = num[i];
num[i] = tmp;
}
}
7 Hill sort
- Define a variable
gap
that represents the interval of elements currently to be sorted, and the initial value is the length of the arraylength
. - Calculate the new interval, the formula is
gap = gap / 3 + 1
, so that the interval can be gradually reduced until it is 1. - Perform the following steps for each interval:
- Define a variable
i
that represents the starting position of the current interval to be sorted, with an initial value of0
. - Starting from the current position, traverse the elements in each interval in the array backwards. If an element smaller than the element in the previous interval is found, save it in a temporary variable tmp and perform the following steps:
- Define a variable
k
that represents the position of the element within the last interval of the sorted part. The initial value is the current position minus the interval, that isk = j - gap
. - Compare the size of the element in the last interval of the sorted part
num[k]
with the size of the element to be insertedtmp
. If the former is greater than the latter, the former will be moved backward by one interval, which will benum[k]
assigned tonum[k+gap]
, andk
the interval will be subtracted to continue the comparison; If not, it means that the position to be inserted is found and the loop is broken out. - Assign the element to be inserted
tmp
to the found position, which is about totmp
be assigned tonum[k+gap]
.
- Define a variable
- Increment the variable
i
by one, indicating that the next interval is to be sorted, and return to step 3.2 to continue traversing and inserting.
- Define a variable
- Repeat steps 2 and 3 until the variable
gap
equals 1. At this time, all elements in the array have been sorted and the algorithm ends.
The advantage of Hill sorting algorithm is that its efficiency is higher than simple insertion sorting, and its time complexity is O ( n 1.3 ) O(n^{1.3})O ( n1.3 ), where n is the length of the array. The disadvantage is that it is unstable and has an impact on the selection efficiency of different intervals.
void ShellSort(int num[],int length)
{
int gap = length;
do
{
gap = gap / 3 + 1;
for(int i=0;i<gap;i++)
{
for(int j=gap+i;j<length;j+=gap)
{
if(num[j] < num[j-gap])
{
int tmp = num[j];
int k;
for(k=j-gap;(k>=0) && (num[k]>tmp);k-=gap)
{
num[k+gap] = num[k];
}
num[k+gap] = tmp;
}
}
}
} while(gap>1);
}