链表和数组的快速排序

思路

  1. 确定pivot指向最左边位置,确定两个指针,p,q都指向最左边的下一个位置
  2. q指针右移一位,如果判断arr[q]是否比pivot大,如果大,++,如果小,则交换p和q位置
  3. 这样,一直到头,p和q之间就是比pivot大的元素,p左边就比pivot小,将pivot和p-1位置交换
  4. 继续递归
    数组快排
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;
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值