排序算法实例:
冒泡<选择<插值<希尔<快速(效率)
/**
* 冒泡排序
*/
public int [] getIntList(int [] ints){
int from;
//是否循环标记
boolean flag = false;
for (int i = 0; i < ints.length-1; i++) {
for (int j = 0; j <ints.length-1-i ; j++) {
if (ints[j]>ints[j+1]){
flag = true;
from = ints[j];
ints[j] = ints[j+1];
ints[j+1] = from;
}
}
if (!true){
break;
}else {
flag = false;
}
}
return ints;
}
/**
* 选择排序法
* 每次循环拿出最小的一个值放在前面
*/
public int [] getSelectSort(int [] ints){
for (int i = 0; i < ints.length-1; i++) {
//我们每次循环 都假设 第一个值是最小的
int min = ints[i];
//最小值的索引
int minIndex = i;
for (int j = i+1; j < ints.length; j++) {
if (min > ints[j]){ //说明min不是最小 需要换换位
min = ints[j];
minIndex = j;
}
}
//当MinIndex改变了才进行换位操作
if (minIndex != i){
//换位
ints[minIndex] = ints[i];
ints[i] = min;
}
}
return ints;
}
/**
* 插入排序法
*/
public int [] getInsertSort(int [] ints){
for (int i = 1; i < ints.length; i++) {
int insertVal = ints[i];
int insertIndex = i-1; //指向ints[i] 前面的一个数
//insertIndex >= 0 确保数组不越界 如果insertVal < ints[insertIndex] 说明还没到位
while(insertIndex >= 0 && insertVal < ints[insertIndex]){
ints[insertIndex] = ints[insertIndex+1];
insertIndex--;
}
//1 2 3 4 x 9 7
//_ _ _ _ _ _ _
ints[insertIndex+1] = insertVal;
}
return ints;
}
/**
* 优化希尔排序法
*/
public int [] getHillSortMax(int[] ints){
int temp;
int j;
for (int gap = ints.length/2;gap>0;gap/=2){
for (int i = gap ; i<ints.length ; i++){
j = i;
temp = ints[i];
if (ints[j]<ints[j-gap]){
while (j-gap>=0 && temp < ints[j-gap]){
ints[j] = ints[j-gap];
j-=gap;
}
ints[j] = temp;
}
}
}
return ints;
}
/**
* 快速排序
*/
public void getQuickSort(int[] ints,int start,int end){
if (start<end){
int first = ints[start];
int low = start; //低位索引
int hight = end; //高位索引
//低位索引和高位索引重合时就应该退出循环
while (low<hight){
//如果初始值小于地位值 高位索引-- 直到找到小的
while (low<hight&&first<=ints[hight]){
hight--;
}
//如果高位值 小于初始值 就让它赋值到低位
//(右边赋值给左边)
ints[low] = ints[hight];
while (low<hight&&ints[low]<=first){
low++;
}
ints[hight] = ints[low];
}
ints[low] = first;
//递归处理小的数字
getQuickSort(ints,start,low);
//递归处理大的数字
getQuickSort(ints,low+1,end);
}