排序在工作中也是经常用到,网上也是有很多的教程,在这里就自己总结了几种排序的算法。
public class SelectionSort {
public static boolean less(Comparable v,Comparable w){
return v.compareTo(w) < 0;
}
//交换
public static void exch(Comparable[]a,int i,int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
//打印数组
public static void show(Comparable[]a){
for (int i = 0;i" ");
}
StdOut.println();
}
//测试数组是不是有序
public static boolean isSorted(Comparable[]a){
for (int i = 1;iif (less(a[i],a[i-1]))
return false;
return true;
}
public static void sort(Comparable[] array) {
//将数组array按照升序排列
int N = array.length;
for (int i = 0;i//将array[i]和array[i+1...N]中最小的元素交换
int min = i;//最小的下标
for (int j = i+1;jif (less(array[j],array[min])) {
min = j;
}
}
//交换
exch(array,i,min);
}
}
public static void main(String[] args) {
String[] a = {"f","a","x"};
sort(a);
show(a);
}
}
上述的代码中交换的方法写在内循环的外边,每次交换就能排定一个元素,因此交换的次数是N,所以算法的时间效率取决与比较的次数。
**
public class InsertionSort {
public static boolean less(Comparable v,Comparable w){
return v.compareTo(w) < 0;
}
//交换
public static void exch(Comparable[]a,int i,int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
//打印数组
public static void show(Comparable[]a){
for (int i = 0;i" " );
}
StdOut.println();
}
//测试数组是不是有序
public static boolean isSorted(Comparable[]a){
for (int i = 1;iif (less(a[i],a[i-1]))
return false;
return true;
}
public static void sort(Comparable[]array){
//按照升序排列
int N = array.length;
for (int i = 1;i//将array[i]插入到array[i-1],array[i-2],array[i-3]...中
for (int j = i;j>0 && less(array[j],array[j-1]);j--) {
exch(array,j,j-1);
}
}
}
public static void main(String[] args) {
String[] a = {"f","a","x"};
sort(a);
show(a);
}
}
3.希尔排序
希尔排序是一种基于插入排序的快速排序,希尔排序就是插入排序的优化。希尔排序的思想就是使数组中的任意间隔为h的元素都是有序的,这样的数组被称为h有序数组,一个h有序数组就是h个互相独立的有序数组组成的大数组。
public class ShellSort {
public static boolean less(Comparable v,Comparable w){
return v.compareTo(w) < 0;
}
//交换
public static void exch(Comparable[]a,int i,int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
//打印数组
public static void show(Comparable[]a){
for (int i = 0;i" " );
}
StdOut.println();
}
//测试数组是不是有序
public static boolean isSorted(Comparable[]a){
for (int i = 1;iif (less(a[i],a[i-1]))
return false;
return true;
}
public static void sort(Comparable[]array){
//升序排列
int N = array.length;
int h = 1;
while (h < N/3)
h = 3*h+1;
while (h >=1 ) {
//将数组变为h有序
for (int i = h;ifor (int j = i;j>=h&&less(array[j],array[j-h]);j-=h) {
exch(array,j,j-h);
}
}
h = h/3;
}
}
public static void main(String[] args) {
String[] a = {"f","a","x"};
sort(a);
show(a);
}
}