归并、快排非递归
归并非递归
非递归归并排序将每一个元素都看作是有序的,然后将这些有序的元素递归
public static void anotherMergeSort(int[] array) {
for(int i = 1;i < array.length;i *= 2) {
merge(array,i);
}
System.out.println(Arrays.toString(array));
}
public static void merge(int[] array,int step) {
int len = array.length;
int s1 = 0;
int e1 = s1 + step - 1;
int s2 = e1 + 1;
int e2 = s2 + step - 1 < len ? s2 + step - 1 : len - 1;
int[] temp = new int[len];
int k = 0;
while(s2 < len) {
while(s1 <= e1 && s2 <= e2) {
if(array[s1] <= array[s2]) {
temp[k++] = array[s1++];
}else {
temp[k++] = array[s2++];
}
}
while(s1 <= e1) {
temp[k++] = array[s1++];
}
while(s2 <= e2) {
temp[k++] = array[s2++];
}
s1 = s2 + 1;
e1 = s1 + step - 1;
s2 = s1 + 1;
e2 = s2 + step - 1 < len ? s2 + step - 1 : len - 1;
}
while(s1 < len - 1) {
temp[k++] = array[s1++];
}
array = Arrays.copyOf(temp,temp.length);
}
快排非递归
快排非递归的实现主要依赖于栈,用栈存储每次划分的范围,然后对每个范围内再进行基准划分。
public static void anotherQuickSort (int[] array) {
Stack<Integer> stack = new Stack();
int left = 0;
int right = array.length - 1;
stack.push(right);
stack.push(left);
while(!stack.isEmpty()) {
//栈先入后出,先出栈的是start
//出栈和入栈顺序要搞清楚
int start = stack.pop();
int end = stack.pop();
int pov = partition(array,start,end);
//找到基准后,按照基准划分
stack.push(end);
stack.push(pov + 1);
stack.push(pov - 1);
stack.push(start);
}
}
public static int partition(int[] array,int start,int end) {
int temp = array[start];
while(start < end) {
while(start < end && array[end] >= temp) {end--;}
array[start] = array[end];
while(start < end && array[start] <= temp) {start++;}
array[end] = array[start];
}
array[start] = temp;
return start;
}