常用排序
平常进行数组排序时,我们一般常用冒泡、选择、插入等排序算法,今天手敲了冒泡排序、选择排序、插入排序、希尔排序的java实现,以及简单的测试算法实现需要的时间,如有遗漏,敬请告知。
话不多说直接上代码。
排序类
public class Sort {
/**
* @param int型数组a
* 冒泡排序
*/
public static void bubble(int[] a) {
long start = System.nanoTime();
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length-i-1; j++) {
if(a[j] > a[j+1]) {
int temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
long end = System.nanoTime();
int excuteTime=(int)(end - start);
System.out.print("冒泡排序为:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("执行时间为:"+excuteTime+"纳秒");
}
/**
* @param int型数组a
* 选择排序
*/
public static void selectionSort(int[] a) {
int temp;
int minIndex;
long start = System.nanoTime();
for (int i = 0; i < a.length-1; i++) {
minIndex = i;
for (int j = i+1; j < a.length; j++) {
if(a[j]<a[minIndex]) {
minIndex = j;
}
}
temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
long end = System.nanoTime();
int excuteTime=(int)(end - start);
System.out.print("选择排序为:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("执行时间为:"+excuteTime+"纳秒");
}
/**
* @param int型数组a
* 插入排序
*/
public static void InsertionSort(int[] a) {
long start = System.nanoTime();
for (int i = 1; i < a.length; i++) {
int preIndex = i-1;
int current = a[i];
while(preIndex >= 0 &¤t < a[preIndex]) {
a[preIndex + 1] = a[preIndex];
preIndex--;
}
a[preIndex+1] = current;
}
long end = System.nanoTime();
int excuteTime=(int)(end - start);
System.out.print("插入排序为:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("执行时间为:"+excuteTime+"纳秒");
}
/**
* @param int型数组a
* 希尔排序shell
*/
public static void ShellSort(int[] a) {
int aLen = a.length;
long start = System.nanoTime();
for (int gap = (int) aLen / 2; gap > 0; gap = (int) gap / 2) {
for (int i = gap; i < a.length; i++) {
int j = i;
int current = a[i];
if(j - gap >0 && current <a[j -gap]) {
a[j] = a[j -gap];
j = j-gap;
}
a[j] = current;
}
}
long end = System.nanoTime();
int excuteTime=(int)(end - start);
System.out.print("希尔排序为:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println("执行时间为:"+excuteTime+"纳秒");
}
}