二分法
package com.ycit.sortSelect;
/**
* @author Administrator
* 二分法排序
*/
public class BinaryInsertSort {
public void sort(int a[]){
for(int i = 0;i
int left = 0; //left为有序数组的第一个下标
int right = i-1; //right为将要比较的数在数组的下标-1 ,即有序数组的最后一个下标
int mid = 0;
int temp = 0;
temp=a[i];// temp和有序数组做比较
while(left<=right){ //如果left小于right则一直寻找,直到left 大于 right
mid=(left+right)/2;
if(a[i]
right=mid-1; //若待比较的值比mid小 ,left不变 right变为mid-1
}else{
left=mid+1;//若待比较的值比mid大,right不变 left变为mid+1
}
}
for(int j =i-1;j>=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
min = array[i];
for(int j = i;j
if(min
min = array[j];
temp = array[i];
array[i] = min;
array[j] = temp;
}
}
}
for(int sort : array){
System.out.println(sort);
}
}
public static void main(String[] args) {
SelectSort s = new SelectSort();
s.selectSort(new int[]{8,3,4,5,7,1,12,33,15});
}
}
直接插入排序
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
int temp = array[i]; //temp和数组前面的有序数组进行比较
for(j=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
System.out.println("排序后"+array[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);
}
}
}