Java 排序算法实现

package test;

import java.util.Scanner;

public class JavaSort {

	public static void quickSort(int a[], int left, int right) {
		if (a == null || a.length == 0)
			return;
		if (left >= right)
			return;

		int i = left;
		int j = right;

		int key = a[left];

		while (i < j) {
			while (i < j && key <= a[j]) {
				j--;
			}
			a[i] = a[j];

			while (i < j && key >= a[i]) {
				i++;
			}
			a[j] = a[i];
		}

		a[i] = key;
		quickSort(a, left, i - 1);
		quickSort(a, i + 1, right);
	}

	public static void InsertSort(int[] a) {
		if (a == null || a.length == 0)
			return;
		int i, j, key;

		for (i = 1; i < a.length; i++) {
			key = a[i];
			j = i - 1;
			while (j >= 0 && a[j] > key) {
				a[j + 1] = a[j];
				j--;
			}
			a[j + 1] = key;
		}
	}

	public static void BubbleSort(int[] a) {
		if (a == null || a.length == 0)
			return;
		int i, j;
		for (i = 0; i < a.length; i++) {
			for (j = a.length - 2; j >= i; j--) {
				if (a[j] > a[j + 1]) {
					a[j] = a[j + 1] ^ a[j];
					a[j + 1] = a[j + 1] ^ a[j];
					a[j] = a[j + 1] ^ a[j];
				}
			}
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		String[] strs = line.split(",");
		int nums[] = new int[strs.length];
		int i = 0;

		for (String s : strs) {
			nums[i++] = Integer.parseInt(s);
		}

		System.out.println("quick sort");
		quickSort(nums, 0, nums.length - 1);

		for (int j : nums) {
			System.out.println(j);
		}

		System.out.println("insert sort");
		InsertSort(nums);
		for (int j : nums) {
			System.out.println(j);
		}
		
		
		System.out.println("bubble sort");
		BubbleSort(nums);
		for (int j : nums) {
			System.out.println(j);
		}

		sc.close();
	}

}

 

posted @ 2015-08-12 10:22  fangying  阅读(159)  评论(0编辑  收藏  举报