<?php $n = 8; $min = 1; $max = 100; $data = createData($n, $min, $max); echo "随机生成数组:"; print_r($data); echo "<br />"; bubble_sort($data, $n); //生成一个随机数组成的不重复数组 function createData($n, $min, $max){ $bigarr = range($min, $max); $arrkey = array_rand($bigarr, $n); //返回键名 for($i=0; $i<count($arrkey); $i++){ $arr[] = $bigarr[$arrkey[$i]]; } return $arr; } //冒泡排序函数 function bubble_sort($data, $n) { $flag = 0; for($i=0; $i<$n-1; $i++){ for($j=0; $j<$n-$i-1; $j++){ if($data[$j+1] < $data[$j]){ $flag = 1; $temp = $data[$j]; $data[$j] = $data[$j+1]; $data[$j+1] = $temp; } } if (!$flag){ break; } $flag = 0; echo "排序过程 ".($i+1)." 步:"; print_r($data); echo "<br/>"; } echo "排序后的结果:"; print_r($data); } ?>
#include<iostream> #include<stdlib.h> #include<time.h> using namespace std; int createData(int arr[], int n, int min, int max); void bubble_sort(int *a, int n); int main() { int arr[100]; int n=6; int min=2; int max=12; createData(arr, n, min, max); for (int i=0; i<n; i++) cout << arr[i] << " "; cout << endl; bubble_sort(arr, n); for (int j=0; j<n; j++) cout << arr[j] << " "; cout << endl; return 1; } //生成一个随机数组成的不重复数组 int createData(int arr[], int n, int min, int max) { srand(time(NULL)); int i,j,flag; for(i=0; i<n; i++){ do{ int num = min + rand()%(max-min+1); arr[i] = num; flag = 0; for(j=0; j<i; j++){ if( arr[i] == arr[j]) flag = 1; } }while(flag); } return 1; } //冒泡排序函数 void bubble_sort(int *a, int n) { bool flag = true; int k = n; while(flag) { flag = false; for(int i=1; i<k; i++) { if(a[i-1] > a[i]) { int tmp = a[i]; a[i] = a[i-1]; a[i-1] = tmp; flag = true; } } k--; } }
原文地址:http://blog.csdn.net/guugle2010/article/details/41309341