首页 > 编程语言 > 详细

几种简单的排序算法(JAVA)

时间:2017-01-20 18:53:25      阅读:190      评论:0      收藏:0      [点我收藏+]
package com.hdwang;

import java.util.Arrays;

/**
 * Created by admin on 2017/1/20.
 */
public class Sort {

    /**
     * 冒泡排序(最小数冒泡)
     * @param array 数组
     */
    public void bubbleSort(int[] array){
        for(int i=0;i< array.length-1;i++){ //比多少次
            for(int j= i+1;j<array.length;j++){ //每次循环,将最小数提前
                if(array[i]>array[j]){ //小数冒泡
                    int tmp = array[i];
                    array[i] = array[j];
                    array[j] = tmp;
                }
            }
        }
    }

    /**
     * 选择排序(选择最小值置前,较冒泡排序空间占用多,速度快(少了交换))
     * @param array 数组
     */
    public void selectSort(int[] array){
        for(int i=0;i<array.length-1;i++){
            int minIndex = i;
            for(int j=i+1;j<array.length;j++){
               if(array[j]<array[minIndex]){
                   minIndex = j; //最小值位置
               }
            }
            //交换最小值与第i位的值
            if(minIndex != i){
                int tmp = array[minIndex]; //最小值
                array[minIndex] = array[i];
                array[i] = tmp;
            }
        }
    }

    /**
     * 插入排序(大数后移,小数插入前面)
     * @param array 数组
     */
    public void insertSort(int[] array){
        for(int i=1;i< array.length;i++){
            int tmp = array[i]; //暂存i位的元素,空出来
            int j = i;
            for(;j > 0 && tmp < array[j-1]; j--){  //前面的大数移到后面来
                    array[j] = array[j-1];
            }
            array[j] = tmp; //tmp插入准确位置
        }
    }

    public static void main(String[] args) {
        int[] array = {2,3,1,6,9,5,4,2};
        System.out.println(Arrays.toString(array));

        Sort sort = new Sort();
        sort.bubbleSort(array);
        System.out.println(Arrays.toString(array));
        sort.selectSort(array);
        System.out.println(Arrays.toString(array));
        sort.insertSort(array);
        System.out.println(Arrays.toString(array));

    }
}

 

几种简单的排序算法(JAVA)

原文:http://www.cnblogs.com/hdwang/p/6323490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!