冒泡排序的基本思想:比较相邻的元素,如果反序则交换。通过第一趟排序能找出最大的元素,并使最大的元素移至最后一位,然后通过第二次排序使次大的元素移至倒数第二位,以此类推,直至所有元素有序。

程序代码如下:

#include<iostream>
using namespace std;

void print(int arr[], int n)
{  
    for(int j= 0; j<n; j++)
	{  
           cout<<arr[j] <<"  ";  
        }  
    cout<<endl;  
}  

void BubbleSort(int arr[], int n)
{
    for (int i = 0; i < n - 1; i++)
	{
            for (int j = 0; j < n - i - 1; j++)
	        {
                    if (arr[j] > arr[j + 1]) 
			{
                            int temp = arr[j];
                            arr[j] = arr[j + 1];
                            arr[j + 1] = temp;
                        }
                 }
         }
}

int main()
{  
    int s[10] = {8,1,9,7,2,4,5,6,10,3};  
    cout<<"初始序列:";  
    print(s,10);  
    BubbleSort(s,10);  
    cout<<"排序结果:";  
    print(s,10);  
    system("pause"); 
} 

时间复杂度:\large O(n^2)      空间复杂度:\large O(1)       稳定

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐