常用排序算法之冒泡排序

xiaoxiao2021-02-28  142

冒泡排序:

基本思想:在要排序的一组数中,对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。就像水中轻的气泡冒出来,重的物体沉下去一样。 程序实现

#include<iostream> using namespace std; void print(int a[], int n){ for(int j= 0; j<n; j++) { cout<<a[j] <<" "; } cout<<endl; } void bubbleSort(int a[], int n){ for(int i =0 ; i< n-1; ++i) { for(int j = 0; j < n-i-1; ++j) { if(a[j] > a[j+1]) { int tmp = a[j] ; a[j] = a[j+1] ; a[j+1] = tmp; } } } } int main() { int a[8]={49,38,65,97,76,13,27,49}; print(a,8); bubbleSort(a,8); print(a,8); system("pause"); return 0; }

分析

49

38

38

38

38

38

13

38

49

49

49

49

13

27

65

65

65

13

13

27

38

97

76

13

27

27

49

49

76

13

27

49

49

49

49

13

27

49

65

65

65

65

27

49

76

76

76

76

76

49

97

97

97

97

97

97

初始关键字

第一趟排序后

第二趟排序后

第三趟排序后

第四趟排序后

第五趟排序后

第六趟排序后

转载请注明原文地址: https://www.6miu.com/read-40647.html

最新回复(0)