码迷,mamicode.com
首页 > 编程语言 > 详细

java---数字排序

时间:2014-10-26 11:33:14      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   java   for   sp   数据   div   

Java中利用数组进行数字排序一般有4种方法:选择排序法、冒泡法、快速排序法、插入排序法。

选择排序是先将数组中的第一个数作为最大或最小数,然后通过循环比较交换最大数或最小数与一轮比较中第一个数位置进行排序;

冒泡排序也是先将数组中的第一个数作为最大或最小数,循环比较相邻两个数的大小,满足条件就互换位置,将最大数或最小数沉底;

快速排序法主要是运用Arrays类中的Arrays.sort方法()实现。

插入排序是选择一个数组中的数据,通过不断的插入比较最后进行排序。

选择排序法

package com.lovo;

public class Test01 {

    public static void main(String[] args) {
        int[] a = new int[5];
            for(int i = 0; i < a.length; i++) {
            a[i] = (int) (Math.random() * 99 + 1);
            System.out.print(a[i] + "  ");
        }
        // 简单选择排序
        for(int i = 0; i < a.length - 1; i++) {
            int minIndex = i;
            for(int j = i + 1; j < a.length; j++) {
                if(a[j] < a[minIndex]) {
                    minIndex = j;
                }
            }
            if(minIndex != i) {
                int temp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = temp;
            }
        }
        

        for(int x : a) {
            System.out.print(x + "  ");
        }
    }
}

 

冒泡排序法

package com.lovo;

public class Test02 {

	public static void main(String[] args) {
		int[] a = new int[5];
		for(int i = 0; i < a.length; i++) {
			a[i] = (int) (Math.random() * 99 + 1);
			System.out.print(a[i] + "  ");
		}
		// 冒泡排序
		
		boolean swapped = true;	// 有没有发生过交换
		for(int i = 1; swapped && i <= a.length - 1; i++) {
			swapped = false;	
			for(int j = 0; j < a.length - i; j++) {
				if(a[j] > a[j + 1]) {
					int temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
					swapped = true;
				}
			}
		}
		
		
		for(int x : a) {
			System.out.print(x + "  ");
		}
	}
}

 

快速排序法

package com.lovo;

import java.util.Arrays;

public class Test03 {
	// 快速排序法
	public static void main(String[] args) {
		int[] a = new int[5];
		System.out.print("排序前: ");
		for (int i = 0; i < a.length; i++) {
			a[i] = (int) (Math.random() * 99 + 1);
			System.out.print(a[i] + "  ");
		}
		System.out.print("\n排序后:");
		Arrays.sort(a); // 进行排序
		for (int x : a) {
			System.out.print(x + "  ");
		}
	}
}

 

java---数字排序

标签:style   blog   color   ar   java   for   sp   数据   div   

原文地址:http://www.cnblogs.com/iguo/p/4051704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!