起泡排序(bubble sort)

来源:互联网 发布:stc检测不到单片机 编辑:程序博客网 时间:2024/05/03 01:53

起泡排序
        起泡排序比较相邻元素,若为逆序,则交换元素,这种排序一般需要多次遍历数据。在第一次便利中,比较数组前两项,若为逆序,则进行交换;则比较下一对元素,即数组位置2和位置3,若为逆序,则进行交换,继续此过程,每次比较和交换两个元素,直到数组结束。

#include<iostream>using namespace std;void sort(int arr[],int size);int main(){const int SIZE=10;int aarray[SIZE]={4,8,9,6,3,2,15,7,1,12};for(int i=0;i<SIZE;i++)cout<<"the "<<i+1<<"th item is"<<aarray[i]<<endl;sort(aarray,SIZE);cout<<"the sorted array aarray is :"<<endl;for(int i=0;i<SIZE;i++)cout<<"the "<<i+1<<"th item is "<<aarray[i]<<endl;return 0;}void sort(int arr[],int size){bool sorted=false;for(int i=1;(i<size)&&(!sorted);i++){sorted=true;int swapmax;for(int j=0;j<size-i;j++){if(arr[j]>arr[j+1]){swapmax=arr[j];arr[j]=arr[j+1];arr[j+1]=swapmax;sorted=false;}}}}

原创粉丝点击