Commonly used sorting and search algorithms for interviews

1 Binary search

  1. Define two variables leftand right, representing the left and right boundaries of the array respectively. The initial values ​​are respectively 0and len - 1, where lenis the length of the array.
  2. Calculate the middle position of the array mid, the formula is , and determine whether (left + right) / 2the element at that position in the array is equal to the target value .num[mid]target
  3. If they are equal, the target value is found and returned midas the result.
  4. If they are not equal, compare num[mid]the targetsize of the sum. If num[mid] < target, it means that the target value is in the right half of the array, so the left boundary is updated as mid + 1; if num[mid] > target, it means that the target value is in the left half of the array, so the right boundary is updated as mid - 1.
  5. 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

  1. Define a variable ithat represents the position of the last element in the unsorted part of the array, with an initial value of length - 1, where lengthis the length of the array.
  2. 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 element num[j+1], swap their positions, so that the larger element can be moved backward.
  3. 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.
  4. Decrement the variable iby 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.
  5. Repeat steps 2 to 4 until the variable iis 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

  1. Define a function MaxHeapwhose 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 are numthe array, startthe starting position of the adjustment, endand the end position of the adjustment.
  2. In the function MaxHeap, define two variables dadand son, respectively representing the positions of the parent node and child node currently to be adjusted. The initial values ​​are respectively and start( start * 2 + 1because the array subscript starts from 0, so the left child node is the parent node multiplied by 2 plus 1 ).
  3. 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.
  4. 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).
  5. 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).
  6. Repeat steps 3 to 5 until adjustment is complete or return.
  7. Define a HeapSortfunction that performs heap sort on an array. There are two parameters of the function, which are numthe array and lenthe length of the array.
  8. Starting from the middle of the array and executing the function on each element MaxHeapin turn, the entire array can be adjusted into a large root heap (i.e. the first element is the largest element).
  9. 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 MaxHeapresizes the remainder into a large root heap (i.e. the first element is the largest element of the remainder).
  10. 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

  1. Define a variable ito represent the position of the element currently to be inserted. The initial value is 1, indicating starting from the second element of the array.
  2. Save the current element to be inserted num[i]in a temporary variable tmpso it won't be overwritten.
  3. Define a variable jthat represents the position of the last element of the sorted part, with an initial value of i - 1.
  4. Compare the size of the last element of the sorted part num[j]with the size of the element to be inserted tmp. If the former is greater than the latter, move the former one backward, which is about to num[j]be assigned to num[j+1], and jsubtract one; if not, it means that it is found. The position to insert, break out of the loop.
  5. Assign the element to be inserted tmpto the found position, which is about to tmpbe assigned to num[j+1].
  6. Add one to the variable ito indicate that the next element is to be inserted, and return to step 2 to continue comparison and movement.
  7. Repeat steps 2 to 6 until the variable iis 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

  1. Define a QuickSortfunction that performs quick sorting on a portion of an array. There are three parameters of the function, which are numthe array, startthe starting position of sorting, endand the end position of sorting.
  2. 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.
  3. Define two variables iand j, respectively representing the left boundary and right boundary of the current part to be divided. The initial values ​​are startrespectively end.
  4. Select the first element in the array num[i]as the base value and save it in a temporary variable basenumso that it is not overwritten.
  5. 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.
  6. 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.
  7. 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.
  8. 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 value QuickSort.
  9. 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

  1. Define a variable ito represent the current position to be selected. The initial value is 0, which means starting from the first element of the array.
  2. Define a variable minto represent the position of the current smallest element, with an initial value of i.
  3. 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 minelement in the current range can be found.
  4. Swap the current position and the value of the smallest element, which will be num[min]assigned to num[i], and which will num[i]be assigned to num[min], so that the smallest element is placed in the correct position.
  5. iAdd 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.
  6. Repeat steps 2 to 5 until the variable iis 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

  1. Define a variable gapthat represents the interval of elements currently to be sorted, and the initial value is the length of the array length.
  2. Calculate the new interval, the formula is gap = gap / 3 + 1, so that the interval can be gradually reduced until it is 1.
  3. Perform the following steps for each interval:
    • Define a variable ithat represents the starting position of the current interval to be sorted, with an initial value of 0.
    • 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 kthat 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 is k = 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 inserted tmp. If the former is greater than the latter, the former will be moved backward by one interval, which will be num[k]assigned to num[k+gap], and kthe 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 tmpto the found position, which is about to tmpbe assigned to num[k+gap].
    • Increment the variable iby one, indicating that the next interval is to be sorted, and return to step 3.2 to continue traversing and inserting.
  4. Repeat steps 2 and 3 until the variable gapequals 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);
}

Guess you like

Origin blog.csdn.net/qq_44528283/article/details/133501105