C++ sorting algorithm exchange sort

Preface

Exchange sorting has two so-called exchanges, bubble sorting and quick sorting. The comparison result of the key values ​​of two records in the sequence is used to swap the positions of the two records in the sequence.

1. Bubble sort

Baidu Encyclopedia:

----Bubble Sort is a relatively simple sorting algorithm in the field of computer science.
----It has repeatedly visited the column of elements to be sorted, compared two adjacent elements in turn, and exchanged them if the order (such as from largest to smallest, first letter from Z to A) is wrong. The work of visiting elements is repeated until no adjacent elements need to be exchanged, that is to say, the element column has been sorted.

Sorting principle:
judge the size of two adjacent values, if the latter value is less than the previous value, exchange (ascending order), as shown in the figure:
Insert picture description here
code

void bubble(int demoList[],int lengthList)
{
    
    
    int j,k,demoData;
    for(int i=0;i<lengthList-1;i++)
    {
    
    
        for(j=0;j<lengthList-i-1;j++)
        {
    
    
            if(demoList[j]>demoList[j+1])
            {
    
    
                demoData=demoList[j];   
                demoList[j]=demoList[j+1]; 
                demoList[j+1]=demoData;
                for(k=0;k<lengthList;k++) //每次交换输出数组
                {
    
    
                    cout<<demoList[k]<<" ";
                }
                cout<<"\n";  
            }
        }      
    }
}

Output: The
test data is: demoList[10]={10,2,3,1,5,4,8,6,9,7};

Summary:

  • (1) Algorithm average time complexity: O(n 2 )
  • (2) Features:
    -Stable sorting
    -Can be used for chain storage structure
    -More moves and poor performance

2. Quick sort

Guess you like

Origin blog.csdn.net/xinzhilinger/article/details/109052501