知识积累--常见排序算法

  1. 选择排序
	public static void selectSort(int []a){
		int i,j;
		int temp=0,flag=0;
		int n=a.length;
		for(i=0;i<n;i++){
			temp=a[i];
			flag=i;
			for(j=i+1;j<n;j++){
				if(a[j]<temp){
					temp=a[j];
					flag=j;
				}
			}
			if(flag!=i){
				a[flag]=a[i];
				a[i]=temp;
			}
		}
	
  1. 插入排序
	public static void insertSort(int []a) {
      if(a!=null){
    	  for(int i=1;i<a.length;i++){
    		  int temp=a[i],j=i;
    		  
    		  if(a[j-1]>temp){
    			  while(j>=1&&a[j-1]>temp){
    				  a[j]=a[j-1];
    				  j--;
    			  }
    		  }
    		  //第一步先把a[0]和a[1]较小的放在a[0]中
    		  a[j]=temp;
    	  }
      }
	}
  1. 冒泡排序
	public static void bubbleSort(int []a){
		//循环优化之代码外提减少对象创建
		//冒泡排序分为从左往右或者从右往左
		//我自己写的是从左往右,因此每轮过后从右开始一个个就不加入循环
		//方向问题一定要注意
		//如果我循环j=i开始,就代表每轮我要从右往左开始一轮,不然会出错,所以j要么等于0开始,要么=length-1开始
		int temp;
		for (int i=0;i<a.length-1;i++){
			for(int j=i;j<a.length-2;j++){
				if(a[j]>a[j+1]){
					temp=a[j];
					a[j]=a[j+1];
					a[j+1]=temp;
				}
			}
		}		
	}
  1. 快速排序(重要 )
    参考文章链接:https://blog.csdn.net/v123411739/article/details/80071521
    注意:当初始的序列整体或局部有序时,快速排序的性能将会下降
package com.spc.algorithm;

public class QuickSort {
	public static void sort(int[] array, int low, int high) {
		int i, j;
		int index;
		if (low > high)
			return;
		i = low;
		j = high;
		index = array[i];
		while (i < j) {
			while (i < j && array[j] > index) {
				j--;
			}
			if (i < j) {
				array[i++] = array[j];
			}
			while (i < j && array[i] < index) {
				i++;
			}
			if (i < j) {
				array[j--] = array[i];
			}
		}
		//array[i]是中间值
		array[i] = index;
		sort(array, low, i - 1);
		sort(array, i + 1, high);
	}

	public static void quicksort(int[] array) {
		sort(array, 0, array.length - 1);
	}
	public static void main(String[] args) {
		int i=0;
		int a[]={5,4,9,8,7,6,0,1,3,2};
		int len=a.length;
		quicksort(a);
		for(i=0;i<len;i++){
			System.out.println(a[i]);
		}
	}
}

  1. 二分查找
package com.ls.binarysearch;

import java.util.Arrays;
import java.util.Scanner;

public class TestBinarySearch {
    public  static void main(String[] args){
    int[] array ={80, 53, 63, 5, 81, 84, 88, 91, 94};
           //对数组a排序
        //Arrays.sort(a)优化的快速排序算方法
        Arrays.sort(array);
        System.out.println("查找的值:");
        int t = new Scanner(System.in).nextInt();
        int i = binarySearch(array, t);
        System.out.println(i);

    }
  
    private static int binarySearch(int[] array, int t){
        int lo = 0,mid,hi= array.length-1;
        while (lo<=hi){
            mid=(lo+hi)/2;
            if(array[mid]<t){
                lo=mid+1;
            }else if (array[mid]>t){
                hi=mid-1;
            }else {
                return mid;
            }
        }
        return -1;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值