算法入门->冒泡排序->C/C++ 语言实现

来源:互联网 发布:无root修改手机mac地址 编辑:程序博客网 时间:2024/06/09 20:48
#include<stdio.h>#defineSIZE8 void bubble_sort(int a[],int n); void bubble_sort(int a[],int n)//n为数组a的元素个数{    int i,j,temp;    for(j=0;j<n-1;j++)        for(i=0;i<n-1-j;i++)        {            if(a[i]>a[i+1])//数组元素大小按升序排列            {                temp=a[i];                a[i]=a[i+1];                a[i+1]=temp;            }        }}int main(){    int number[SIZE]={95,45,15,78,84,51,24,12};    int i;    bubble_sort(number,SIZE);    for(i=0;i<SIZE;i++)    {        printf("%d",number[i]);    }    printf("\n");}
#include <iostream>using namespace std;template<typename T> //整数或浮点数皆可使用,若要使用物件时必须设定大于的运算子功能void bubble_sort(T arr[], int len) { int i, j; T temp; for (i = 0; i < len - 1; i++) for (j = 0; j < len - 1 - i; j++) if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; }}int main() { int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 }; int len = (int) sizeof(arr) / sizeof(*arr); bubble_sort(arr, len); for (int i = 0; i < len; i++) cout << arr[i] << ' '; cout << endl; float arrf[] = { 17.5, 19.1, 0.6, 1.9, 10.5, 12.4, 3.8, 19.7, 1.5, 25.4, 28.6, 4.4, 23.8, 5.4 }; len = (int) sizeof(arrf) / sizeof(*arrf); bubble_sort(arrf, len); for (int i = 0; i < len; i++) cout << arrf[i] << ' '; return 0;}


0 0