Common sorting algorithm finishing 1 (C++ implementation)

1. Bubble sort

  • Time complexity O(n2)
  • Space complexity O(1)

  The basic idea of ​​the algorithm:

  • Swap adjacent elements, a total of n-1 rounds, each round exchanges n-1-i elements

  C++ implementation:

  • int* bubbleSort(int* A, int n) {
        for(int i=0;i<n-1;i++)
        {
            for(int j=0;j<n-1-i;j++)
            {
                if(A[j]>A[j+1])
                    swap(A[j],A[j+1]);
            }
        }
        return A;

    }

2. Selection sort

  • Time complexity O(n2)
  • Space complexity O(1)

  The basic idea of ​​the algorithm:

  • Divide elements into two categories: unsorted and sorted. Each time the smallest element is selected from the elements to be sorted and inserted at the end of the element to be sorted, it needs to be selected n-1 times.

  C++ implementation:

  • int* selectionSort(int* A, int n) {
        for(int i=0;i<n;i++)
        {
            int min=i;
            for(int j=i+1;j<n;j++)
            {
                if(A[j]<A[min])
                    min=j;
            }
            swap(A[min],A[i]);
        }
        return A;

    }

3. Insertion sort

  • Time complexity O(n2)
  • Space complexity O(1)

   The basic idea of ​​the algorithm:

  • Divide elements into two categories: unsorted and sorted. By default, the first element is put into the sorted class, the traversal starts from the second element, and the current value taken is compared with the sorted element. The method of comparison is to compare from back to front. If the value of the sorted element is not less than the current value, the position of the sorted element is +1, otherwise, the current value is inserted into the sorted class.

   C++ implementation:

  • int* insertionSort(int* A, int n) {
            for(int i=1;i<n;i++)
            {
                int get=A[i];
                int j=i-1;
                while(j>=0&&A[j]>=get)
                {
                    A[j+1]=A[j];
                    j--;
                }
                A[j+1]=get;
            }
            return A;
        }



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325668322&siteId=291194637