package org.idcn.jse;
public class SortAll {
/**
* 冒泡排序,选择排序,插入排序,希尔(Shell)排序 Java的实现
* 2008.11.09
* @author YangL. (http://www.idcn.org)
*/
public static void main(String[] args) {
int[] i = { 1, 5, 6, 12, 4, 9, 3, 23, 39, 403, 596, 87 };
System.out.println("----冒泡排序的结果:");
maoPao(i);
System.out.println();
System.out.println("----选择排序的结果:");
xuanZe(i);
System.out.println();
System.out.println("----插入排序的结果:");
chaRu(i);
System.out.println();
System.out.println("----希尔(Shell)排序的结果:");
shell(i);
}
// 冒泡排序
public static void maoPao(int[] x) {
for (int i = 0; i < x.length; i++) {
for (int j = i + 1; j < x.length; j++) {
if (x[i] > x[j]) {
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
// 选择排序
public static void xuanZe(int[] x) {
for (int i = 0; i < x.length; i++) {
int lowerIndex = i;
// 找出最小的一个索引
for (int j = i + 1; j < x.length; j++) {
if (x[j] < x[lowerIndex]) {
lowerIndex = j;
}
}
// 交换
int temp = x[i];
x[i] = x[lowerIndex];
x[lowerIndex] = temp;
}
for (int i : x) {
System.out.print(i + " ");
}
}
// 插入排序
public static void chaRu(int[] x) {
for (int i = 1; i < x.length; i++) {// i从一开始,因为第一个数已经是排好序的啦
for (int j = i; j > 0; j--) {
if (x[j] < x[j - 1]) {
int temp = x[j];
x[j] = x[j - 1];
x[j - 1] = temp;
}
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
// 希尔排序
public static void shell(int[] x) {
// 分组
for (int increment = x.length / 2; increment > 0; increment /= 2) {
// 每个组内排序
for (int i = increment; i < x.length; i++) {
int temp = x[i];
int j = 0;
for (j = i; j >= increment; j -= increment) {
if (temp < x[j - increment]) {
x[j] = x[j - increment];
} else {
break;
}
}
x[j] = temp;
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
}
**
*递归算法,求n的阶乘
*/
public class Recursion {
int result=1;
public int nRecursion(int n) {
if (n > 0) {
result = result * n;
nRecursion(n-1);
}
return result;
}
}
/**
* 求最大公约数和最小公倍数
*/
public class Convention {
/**
* 求两数的最大公约数
*/
int divisor(int m,int n){
if(m%n==0){
return n;
}else{
return divisor(n,m%n);
}
}
/**
* 求两数的最小公倍数
*/
int gbs(int a,int b){
int gbs = 0;
gbs = a*b/divisor(a,b);
return gbs;
}
}
//二分查找法
public class test {
static int bsearch( int[] a, int v ) {
int l, r;
l = 0; r = a.length-1;
while ( l <= r ) {
int m = (l+r)/2;
if ( a[m] == v ) return m;
else if ( a[m] > v )
r = m-1;
else if ( a[m] < v )
l = m+1;
}
return -1;
}
----------------------------------------------
[color=red]原文引用地址:http://yangl.iteye.com/blog/264627,感谢作者的辛勤劳动[/color]