二分法
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<array.length;i++){
min = array[i];
for(int j = i;j<array.length;j++){
if(min<array[j]){
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<array.length;i++){//数组里面只有一个数的时候不需要排序,所以这边的i从1开始遍历
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<array.length;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);
}
}
}