二分法
package com.ycit.sortSelect;
/**
* @author Administrator
* 二分法排序
*/
public class BinaryInsertSort {
public void sort(int a[]){
for(int i = 0;i=left;j--){
a[j+1]=a[j]; // left 及left后面的数统一往后面挪一个下标
}
if(i!=left){
a[left]=temp;//将待比较值插入到到left中,
}
}
for(int array:a){
System.out.println(array);
}
}
public static void main(String[] args) {
BinaryInsertSort sort = new BinaryInsertSort();
sort.sort(new int[]{49,38,65,97,176,213,227,49,78,34,12,164,11,18,1});
}
}
选择排序
package com.ycit.sortSelect;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
/**
*
* @author Administrator
* 选择排序
*/
public class SelectSort {
public void selectSort(int array[]){
int min;
int temp = 0;
for(int i = 0;i
直接插入排序
package com.ycit.sortSelect;
/**
* @author Administrator
* 2019年4月14日09:38:31
* 直接插入排序
* 时间内复杂度:n n-1 n-2 n-3 n-4 O(n^2/2)
*
*/
public class InsertSort {
public static void main(String args[]){
int [] array = new int[]{-1,9,6,4,2,10};
int j ;
for(int i = 1;i=0;j--){ //这边是从temp要比较的数字从后往前比较,数据前面都是有序的,如果要找到比temp大的数从后往前找的话效率会更高
if(array[j]>temp){
array[j+1]=array[j]; //找到比temp大的数统一往后移一位
}else{
break; //如果找到比temp小的数则退出循环
}
}
//找到比temp小的数的索引+1就是temp要插入的位置
array[j+1]=temp;
}
// 直接排序完成
for(int i =0;i
希尔排序
package com.ycit.sortSelect;
/**
* @author Administrator 希尔排序 2019年4月14日13:51:40
*/
public class HeerSort {
public static void main(String[] args) {
int a[] = { 49, 38, 65, 97, 176, 213, 227, 49, 78, 34, 12, 164, 11, 18, 1 };
int d = a.length / 2; // 设定默认增量
while (true) {
for (int i = 0; i < d; i++) {// 根据增量依次递减提高排序效率
for (int j = i; j + d < a.length; j += d) { // 按增量对数据进行分组并排序
int temp;
if (a[j] > a[j + d]) {
temp = a[j];
a[j] = a[j + d];
a[j + d] = temp;
}
}
}
if (d == 1) {
break;
} // 如果增量等于1时退出比较
d--;
}
for (int afterSort : a) {
System.out.println(afterSort);
}
}
}
冒泡排序
package com.ycit.sortSelect;
/**
* @author Administrator 冒泡排序
*/
public class BubleSort {
public static void main(String[] args) {
int a[] = { 49, 38, 65, 97, 176, 213, 227, 49, 78, 34, 12, 164, 11, 18, 1 };
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
int temp;
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int array : a) {
System.out.println(array);
}
}
}