排序算法 冒泡排序

2013-10-15 11:39  1396人阅读  评论 (0)
Tags: sortC

C语言 冒泡排序

#require <stdio.h>
#define LENGTH 8

void main() {
    int i, j, tmp, sortlen = LENGTH - 1;
    int number[LENGTH] = {95, 45, 15, 78, 84, 51, 24, 12};

    for (i = 0; i < sortlen; i++) {
        for (j = sortlen; j > i; j--) {
            if (number[j] < number[j-1]) {
                tmp = number[j-1];
                number[j-1] =  number[j];
                number[j] = tmp;
            }
        }
    }

    for (i = 0; i < LENGTH; i++) {
        printf("%d ", number[i]);
    }
    printf("\n");
}

Go语言 冒泡排序

package main

import "fmt"

func main() {
    number := []int{95, 45, 15, 78, 84, 51, 24, 12}

    sortlen := len(number) - 1;
    for i := 0; i < sortlen; i++ {
        for j := sortlen; j > i; j-- {
            if (number[j] < number[j-1]) {
                number[j-1], number[j] =  number[j], number[j-1]
            }
        }
    }

    fmt.Println(number)
}

Java语言 冒泡排序

class Sort {
    public static void main(String[] args) {
        int[] number = new int[]{95, 45, 15, 78, 84, 51, 24, 12};
        int tmp, sortlen = number.length - 1;

        for (int i = 0; i < sortlen; i++) {
            for (int j = sortlen; j > i; j--) {
                if (number[j] < number[j-1]) {
                    tmp = number[j-1];
                    number[j-1] =  number[j];
                    number[j] = tmp;
                }
            }
        }

        System.out.println(java.util.Arrays.toString(number));
    }
}

PHP语言 冒泡排序

<?php
$number = array(95, 45, 15, 78, 84, 51, 24, 12);
$sortlen = count($number) - 1;

for ($i = 0; $i < $sortlen; $i++) {
    for ($j = $sortlen; $j > $i; $j--) {
        if ($number[$j] < $number[$j-1]) {
            $tmp = $number[$j-1];
            $number[$j-1] =  $number[$j];
            $number[$j] = $tmp;
        }
    }
}

echo implode(' ', $number);

Python语言 冒泡排序

#!/usr/bin/python

number = [95, 45, 15, 78, 84, 51, 24, 12]
sortlen = len(number) - 1

for i in range(sortlen):
    for j in range(sortlen, i, -1):
        if number[j] < number[j-1]:
            number[j-1], number[j] =  number[j], number[j-1]

print(number)

JavaScript语言 冒泡排序

var number = [95, 45, 15, 78, 84, 51, 24, 12];
var sortlen = number.length - 1;

for (var i = 0; i < sortlen; i++) {
    for (var j = sortlen; j > i; j--) {
        if (number[j] < number[j-1]) {
            var tmp = number[j-1];
            number[j-1] =  number[j];
            number[j] = tmp;
        }
    }
}

console.log(number.join(' '));

C#语言 冒泡排序

没有环境就不写了,跟java的差不多