思路
- 确定pivot指向最左边位置,确定两个指针,p,q都指向最左边的下一个位置
- q指针右移一位,如果判断arr[q]是否比pivot大,如果大,++,如果小,则交换p和q位置
- 这样,一直到头,p和q之间就是比pivot大的元素,p左边就比pivot小,将pivot和p-1位置交换
- 继续递归
数组快排
public class Tset {
public static void main(String[] args) {
int[] arr = new int[]{4,6,7,1,2,8,5};
QuickSort(arr,0,arr.length-1);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
private static void QuickSort(int[] arr,int low,int high){
if (low < high){
int i,j;
i = low+1;
j=low+1;
int pivot = arr[low];
while ( j <= high){
if (arr[j] > pivot){
j++;
}else if (arr[j] < pivot){
swap(arr,i,j);
i++;
j++;
}
}
swap(arr,i-1,low);
QuickSort(arr,low,i-2);
QuickSort(arr,i,high);
}
}
private static void swap(int[] arr,int i ,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
链表快排(试着做力扣148题)
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
public ListNode sortList(ListNode head) {
if(head == null) return head;
ListNode curNode = head;
while(curNode.next != null){
curNode = curNode.next;
}
return quickSort(head,curNode);
}
private ListNode quickSort(ListNode head,ListNode end){
if(head == null || head.next == null || head == end ) return head;
ListNode pivot = head;
ListNode i = head.next;
ListNode j = head.next;
ListNode tmpNode = head;
while(j != end.next){
if(j.val >= pivot.val){
j = j.next;
}else(j.val < pivot.val){
int temp = i.val;
i.val = j.val;
j.val = temp;
tmpNode = i;
i = i.next;
j = j.next;
}
}
//交换
int tmp = pivot.val;
pivot.val = tmpNode.val;
tmpNode.val = tmp;
//递归
quickSort(head,tmpNode);
quickSort(i,end);
return head;
}
}