算法–快速排序
交换排序
要了解快速排序,需要先来了解一下交换排序。所谓交换排序,就是根据序列中两个元素关键字的比较结果来对换两个记录在序列中的位置。
递归
方法1:左右指针法
方法2:前后指针法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| public class QuickSort { public static void main(String[] args) { int[] a = {3,5,2,1,7,6,4}; QuickSort(a,0,6); for(int a1:a){ System.out.print(a1+"--"); } } public static int Partition(int[] a,int low,int high){ int i = low,j = high; int tmp = a[low]; while(i<j){ while(i<j && a[j]>=tmp){ j--; } if(i<j){ a[i]=a[j]; i++; } while(i<j && a[i]<tmp) i++; if(i<j){ a[j] = a[i]; j--; } } a[i] = tmp; return i; } public static void swap(int[] data, int a, int b) { int temp; temp = data[a]; data[a] = data[b]; data[b] = temp; } public static int Partition1(int[] a,int low,int high){ int tmp =a[high]; int p = low-1; for(int i=low;i<high;i++){ if(a[i]<=tmp){ p++; swap(a,p,i); } } swap(a,p+1,high); return p+1; } public static void QuickSort(int[] a,int low,int high){ if(low<high){ int pivot = Partition1(a,low,high); QuickSort(a,low,pivot-1); QuickSort(a,pivot+1,high); }
} }
|
非递归
思路就是利用栈来保存左右区间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public static void GenerQuickSort(int[] arr, int left, int right) { Stack<Integer> stack = new Stack<>(); if(left < right) { stack.push(left); stack.push(right); while(!stack.isEmpty()) { right = stack.pop(); left = stack.pop(); int index = Partition(arr, left, right); if(index-1 > left) { stack.push(left); stack.push(index -1); } if(index+1 < right) { stack.push(index + 1); stack.push(right); } } } }
原文链接:https: 已做修改
|