
package com.test.insertsort;
/**
* 冒泡排序
* @author bjh
*
*/
public class BobSort {
private int[] array;
private int length;
/**
* 构造函数
* @param array
*/
public BobSort(int[] array){
this.array = array;
this.length = array.length;
}
/**
* 打印数组中数据
*/
public void display(){
for(int i : array){
System.out.print(i+" ");
}
System.out.println();
}
/**
* 冒泡排序
*/
public void bobSort(){
for(int i=0;i<length-1;i++){//排序轮数
for(int j=0;j<length-1-i;j++){//比较次数
if(array[j]>array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args){
int[] array = {77,29,28,36,33,25,10};
BobSort bobSort = new BobSort(array);
System.out.println("排序前的数据为:");
bobSort.display();
bobSort.bobSort();
System.out.println("排序后的数据为:");
bobSort.display();
}
}

package com.test.insertsort;
/**
* 选择排序
* @author Administrator
*
*/
public class ChooseSort {
private int[] array;
private int length;
public ChooseSort(int[] array){
this.array = array;
this.length = array.length;
}
/**
* 打印数组中的所有元素
*/
public void display(){
for(int i: array){
System.out.print(i+" ");
}
System.out.println();
}
/**
* 选择排序算法
*/
public void chooseSort(){
for(int i=0; i<length-1; i++){
int minIndex = i;
for(int j=minIndex+1;j<length;j++){
if(array[j]<array[minIndex]){
minIndex = j;
}
}
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
public static void main(String[] args){
int[] array={100,45,36,21,17,13,7};
ChooseSort cs = new ChooseSort(array);
System.out.println("排序前的数据为:");
cs.display();
cs.chooseSort();
System.out.println("排序后的数据为:");
cs.display();
}
}

package com.test.insertsort;
/**
* 插入排序算法:
* 1、以数组的某一位作为分隔位,比如index=1,假设左面的都是有序的.
*
* 2、将index位的数据拿出来,放到临时变量里,这时index位置就空出来了.
*
* 3、从leftindex=index-1开始将左面的数据与当前index位的数据(即temp)进行比较,如果array[leftindex]>temp,
* 则将array[leftindex]后移一位,即array[leftindex+1]=array[leftindex],此时leftindex就空出来了.
*
* 4、再用index-2(即leftindex=leftindex-1)位的数据和temp比,重复步骤3,
* 直到找到<=temp的数据或者比到了最左面(说明temp最小),停止比较,将temp放在当前空的位置上.
*
* 5、index向后挪1,即index=index+1,temp=array[index],重复步骤2-4,直到index=array.length,排序结束,
* 此时数组中的数据即为从小到大的顺序.
*
* @author bjh
*
*/
public class InsertSort {
private int[] array;
private int length;
public InsertSort(int[] array){
this.array = array;
this.length = array.length;
}
public void display(){
for(int a: array){
System.out.print(a+" ");
}
System.out.println();
}
/**
* 插入排序方法
*/
public void doInsertSort(){
for(int index = 1; index<length; index++){//外层向右的index,即作为比较对象的数据的index
int temp = array[index];//用作比较的数据
int leftindex = index-1;
while(leftindex>=0 && array[leftindex]>temp){//当比到最左边或者遇到比temp小的数据时,结束循环
array[leftindex+1] = array[leftindex];
leftindex--;
}
array[leftindex+1] = temp;//把temp放到空位上
}
}
public static void main(String[] args){
int[] array = {38,65,97,76,13,27,49};
InsertSort is = new InsertSort(array);
System.out.println("排序前的数据为:");
is.display();
is.doInsertSort();
System.out.println("排序后的数据为:");
is.display();
}
}
