排序算法

快速排序(数组)

	public static int helperSort(int[]nums,int left,int right){
		int tem=nums[left];
		while(left<right){
			while(left<right && nums[right]>=tem)
				right--;
			nums[left]=nums[right];
			while (left<right && nums[left]<=tem) 
				left++;
			nums[right]=nums[left];
		}
		nums[left]=tem;
		return left;
	}
	public static void quickSort(int[] nums,int left,int right){
		if(left>right) return ;
		int index=helperSort(nums, left, right);
		quickSort(nums, left, index-1);
		quickSort(nums, index+1, right);
	}

快速排序(列表)

package Interview;

public class quicksortList {
	public static class ListNode{
		private int val;
		private ListNode next;
		public ListNode(int val) {
			// TODO Auto-generated constructor stub
			this.val=val;
		}
	}
	public ListNode sort(ListNode start,ListNode end){
		int key=start.val;
		ListNode p=start;
		ListNode q=start.next;
		while(q!=end){
			if(q.val<key){
				p=p.next;
				swap(p,q);
			}
			q=q.next;
		}
		swap(start,p);
		return p;
	}
	public void swap(ListNode p,ListNode q){
		int tem=p.val;
		p.val=q.val;
		q.val=tem;
	}
	public void QuickSort(ListNode start,ListNode end){
		if(start!=end){
			ListNode p=sort(start, end);
			QuickSort(start, p);
			QuickSort(p.next, end);
		}
	}
}

堆排序

public class heapSort {
	public static void adjustHeap(int[]a,int i,int len){
		  int temp, j;
	        temp = a[i];
	        for (j = 2 * i+1; j+1 < len; j = j*2+1) {// 沿关键字较大的孩子结点向下筛选
	            if (j < len && a[j] < a[j + 1])
	                ++j; // j为关键字中较大记录的下标
	            if (temp >= a[j])
	                break;
	            a[i] = a[j];
	            i = j;
	        }
	        a[i] = temp;

	}
	public static void heapSort(int[] a){
		int i;
		for(i=(a.length-2)/2;i>=0;i--){
			adjustHeap(a, i, a.length);
		}
		for(i=a.length-1;i>=0;i--){
			int tem=a[0];
			a[0]=a[i];
			a[i]=tem;
			adjustHeap(a, 0, i-1);
		}
	}
	 public static void main(String[] args) {
	        int a[] = { 51, 46, 20, 18, 65, 97, 82, 30, 77, 50 };
	        heapSort(a);
	        System.out.println(Arrays.toString(a));
	    }
}

冒泡排序

  public static void maopaoSort(int[] nums) {
		int len=nums.length;
		for(int i=0;i<len-1;i++){
			for(int j=0;j<len-i-1;j++){
				if(nums[j+1]<nums[j]){
					int tem=nums[j];
					nums[j]=nums[j+1];
					nums[j+1]=tem;
				}
			}
		}
		
	}

插入排序

public static void insertSort(int[]nums){
		for(int i=0;i<nums.length-1;i++){
			for(int j=i+1;j>0;j--){
				if(nums[j]<nums[j-1]){
					int tem=nums[j];
					nums[j]=nums[j-1];
					nums[j-1]=tem;
				}
			}
		}
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值