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

排序算法(简单排序,冒泡排序)

时间:2014-10-24 22:08:31      阅读:347      评论:0      收藏:0      [点我收藏+]

标签:blog   java   for   div   log   amp   new   算法   as   

int[] a = new int[10];

		for (int i = 0; i < a.length; i++) {
			a[i] = random();

			System.out.print(a[i] + "   ");
		}
		System.out.println();

		int temp = 0;

		// 从小到大

		// 简单选择排序法
		// 方法1
		int minIndex = 0;
		for (int i = 0; i < a.length - 1; i++) {
			minIndex = i;
			for (int j = i + 1; j < a.length; j++) {
				if (a[j] < a[minIndex]) {
					minIndex = j;
				}
				if (minIndex != i) {
					temp = a[i];
					a[i] = a[minIndex];
					a[minIndex] = temp;
				}
			}
		}

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

		// 方法2
		for (int i = 0; i < a.length - 1; i++) {
			for (int j = i + 1; j < a.length; j++) {
				if (a[i] > a[j]) {
					temp = a[i];
					a[i] = a[j];
					a[j] = temp;
				}
			}
		}

		

		System.out.println("从小到大的值为:");
		for (int i = 0; i < a.length; i++) {
			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]) {
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
					swapped = true;
				}
			}
		}

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

	}

  

排序算法(简单排序,冒泡排序)

标签:blog   java   for   div   log   amp   new   算法   as   

原文地址:http://www.cnblogs.com/superyueyue/p/4049184.html

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