最近闲来无事就顺手写写 呵呵 权当练手了
/**
* 一些排序的算法
* @author chengxvdong
*/
public class PaiXv {
/**
* @param args
*/
public static void main(String[] args) {
PaiXv paiXv = new PaiXv();
int[] a = {3,6,9,2,7,8,1};
paiXv.maoPao(a);
paiXv.display(a);
paiXv.xvanZe(a);
paiXv.display(a);
paiXv.chaRu(a);
paiXv.display(a);
paiXv.reversal(a);
paiXv.display(a);
}
/**
* 将数组倒过来(采用的冒泡排序的思想)
* @param shuZu
*/
public void reversal(int[] shuZu){
int length = shuZu.length;
for (int i = 1; i < length; i++) {
for (int j = 0; j < length - i; j++) {
swap(shuZu, j, j + 1);
}
}
}
/**
* 插入排序
* @param shuZu
*/
public void chaRu(int[] shuZu){
int length = shuZu.length;
for (int i = 1; i < length; i++) {
int index = i;
int temp = shuZu[i];
while (index > 0 && shuZu[index - 1] > temp) {
shuZu[index] = shuZu[index - 1];
index--;
}
shuZu[index] = temp;
}
}
/**
* 选择排序
* @param shuZu
*/
public void xvanZe(int[] shuZu){
int length = shuZu.length;
for (int i = 0; i < length; i++) {
int min = i;
for (int j = i + 1; j < length; j++) {
if (shuZu[min] > shuZu[j]) {
min = j;
}
}
swap(shuZu, min, i);
}
}
/**
* 冒泡排序
* @param shuZu
*/
public void maoPao(int[] shuZu){
int length = shuZu.length;
for (int i = 1; i < length; i++) {
for (int j = 0; j < length - i; j++) {
if (shuZu[j] > shuZu[j+1]) {
swap(shuZu, j, j + 1);
}
}
}
}
/**
* 传入数组和要交换的下标
* @param shuZu
* @param index1
* @param index2
*/
public void swap(int[] shuZu,int index1,int index2){
int temp = shuZu[index1];
shuZu[index1] = shuZu[index2];
shuZu[index2] = temp;
}
/**
* 迭代打印数组
* @param shuZu
*/
public void display(int[] shuZu){
int length = shuZu.length;
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < length; i++) {
sbf.append(shuZu[i]).append(",");
}
System.out.println(sbf.substring(0, sbf.length() - 1));
}
}