package test;
import java.util.LinkedList;
public class sort extends Thread{
//快速排序
private static void quickSort(Integer[] a, int start, int end) {
LinkedList<Integer> stack = new LinkedList<Integer>(); // 用栈模拟
if (start < end) {
stack.push(end);
stack.push(start);
while (!stack.isEmpty()) {
int l = stack.pop();
int r = stack.pop();
int index = partition(a, l, r);
if (l < index - 1) {
stack.push(index - 1);
stack.push(l);
}
if (r > index + 1) {
stack.push(r);
stack.push(index + 1);
}
}
}
}
private static int partition(Integer[] a, int p, int r) {
int x = a[r];
int i = p-1;
for(int j=p;j<=r-1;j++) {
if(a[j] <= x) {
i+=1;
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
int t = a[i+1];
a[i] = a[r];
a[r] = t;
return i+1;
}
//冒泡排序
public static Integer[] bubbleSort(Integer[] items) {
for(int i=0;i<items.length-1;i++) {
for(int j=0;j<items.length-i-1;j++) {
if(items[j] > items[j+1]) {
int t = items[j];
items[j] = items[j+1];
items[j+1] = t;
}
}
print(items);
}
return items;
}
//二分插入排序
public static Integer[] binInsertSort(Integer[] items) {
for(int i=1;i<items.length;i++) {
int low = 0;
int high = i-1;
int temp = items[i];
int mid = 0;
//寻找中点进行判断
while(low <= high) {
mid = (low + high)/2;
if(items[mid] > temp) {
high = mid - 1;
}else {
low = mid + 1;
}
}
for(int j=i-1;j>=low;j--) {
items[j+1] = items[j];
}
items[low] = temp;
print(items);
}
return items;
}
//希尔排序
public static Integer[] shellSort(Integer[] items) {
for(int gap=items.length/2;gap>0;gap/=2) {
for(int i=gap;i<items.length;i++) {
int j = i;
int key = items[i];
if(items[j] > items[j-gap]) {
while(j-gap>=0 && key>items[j-gap]) {
items[j] = items[j-gap];
j-=gap;
}
items[j] = key;
}
print(items);
}
}
return items;
}
//插入排序
public static Integer[] insertSort(Integer[] items) {
for(int i=1;i<items.length;i++) {
int key = items[i];
int j = i-1;
while(j>=0 && items[j] > key) {
items[j+1] = items[j];
j-=1;
}
items[j+1] = key;
System.out.print(i+1 + ":");
print(items);
}
return items;
}
//选择排序
public static Integer[] selectSort(Integer[] items) {
for(int i=0;i<items.length-1;i++) {
int k = i;
for(int j=i+1;j<items.length;j++) {
if (items[k] > items[j]) {
k = j;
}
}
int t = items[i];
items[i] = items[k];
items[k] = t;
System.out.print(i+1 + ":");
print(items);
}
return items;
}
private static void print(Integer[] items) {
for(Integer x: items) {
System.out.print(x + ",");
}
System.out.println(" ");
}
public static void main(String[] args) {
Integer[] ss = {2,1,5,9,0,6,8,7,3};
quickSort(ss,0,ss.length-1);
print(ss);
}
}