- package sortDemo;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class SortDemo {
- public static void bubbleSort(int[] array) {
- for (int i = 0; i <array.length - 1; i++) for (int j = 0; j < array.length - i - 1; j++) if (array[j]> array[j + 1]) {
- int temp = array[j];
- array[j] = array[j + 1];
- array[j + 1] = temp;
- }
- }
- public static void chooseSort(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 temp = array[i];
- array[i] = array[j];
- array[j] = temp;
- }
- }
- public static void insertSort(int[] array) {
- int i,
- j,
- temp;
- for (i = 1; i <array.length; i++) {
- temp = array[i];
- j = i - 1;
- while (j>= 0 && array[j]> temp) {
- array[j + 1] = array[j];
- j--;
- }
- array[j + 1] = temp;
- }
- }
- public static void shellSort(int[] array) {
- int i,
- j,
- temp;
- int jump = array.length / 2;
- while (jump != 0) {
- for (i = 1; i <array.length; i++) {
- temp = array[i];
- j = i - jump;
- while (j>= 0 && array[j]> temp) {
- array[j + jump] = array[j];
- j -= jump;
- }
- array[j + jump] = temp;
- }
- jump = jump / 2;
- }
- }
- public static void quickSort(int[] array, int left, int right) {
- int lf = left + 1,
- rg = right;
- if (left <right) {
- while (true) {
- for (int i = left + 1; i <= right; i++) {
- if (array[i]>= array[left]) {
- lf = i;
- break;
- }
- lf++;
- }
- for (int j = right; j>= left; j--) {
- if (array[j] <= array[left]) {
- rg = j;
- break;
- }
- rg--;
- }
- if (lf <rg) {
- int temp = array[lf];
- array[lf] = array[rg];
- array[rg] = temp;
- } else {
- break;
- }
- }
- if (lf>= rg) {
- int temp = array[left];
- array[left] = array[rg];
- array[rg] = temp;
- }
- quickSort(array, left, rg - 1);
- quickSort(array, rg + 1, right);
- }
- }
- public static void main(String[] args) throws IOException {
- BufferedReader in =new BufferedReader(new InputStreamReader(System. in ));
- int[] array = new int[5];
- System.out.println("请依此输入五个整数:");
- for (int i = 0; i < array.length; i++) {
- array[i] = Integer.parseInt( in .readLine());
- }
- System.out.print("排序前:");
- for (int i = 0; i < array.length; i++) {
- System.out.print(" " + array[i]);
- }
- //bubbleSort(array);
- //chooseSort(array);
- //insertSort(array);
- //shellSort(array);
- quickSort(array, 0, array.length - 1);
- System.out.println();
- System.out.print("排序后:");
- for (int i = 0; i < array.length; i++) {
- System.out.print(" " + array[i]);
- }
- // TODO Auto-generated method stub
- }
- }
来源: http://www.jianshu.com/p/5a5f4de4e364