一、冒泡排序
依次比较相邻两个数,将较大的交换到右边,重复此过程,直至有序
package com.algorithm.sort; public class BubbleSort implements Sort { @Override public void sort(int[] arr) { // TODO Auto-generated method stub int exchange = arr.length -1; boolean isExchanged = true; while(isExchanged){ isExchanged = false; int max = exchange; for (int i = 0; i < max; i++){ if (arr[i] > arr[i+1]){ int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; isExchanged = true; exchange = i; } } } } public static void main(String[] args){ int[] arr = {1,3,2,6,9,4,5,7,8,56,7,8,9,3,88}; Sort sort =new BubbleSort(); sort.sort(arr); for(int a: arr){ System.out.print(a + " "); } } }
二、快速排序
将较大的数都交换到右边,较小的数都交换到左边,这样划分成两个序列,再分别对两个序列重复以上过程
package com.algorithm.sort; public class QuickSort implements Sort { @Override public void sort(int[] arr) { // TODO Auto-generated method stub quickSort(arr,0,arr.length-1); } private void quickSort(int[] arr, int first, int end) { if (first < end){ int pos = partition(arr, first, end); quickSort(arr, first, pos-1); quickSort(arr, pos+1, end); } } private int partition(int[] arr, int first, int end){ while (first < end){ //右扫 while (first < end && arr[first] <= arr[end]) end--; if (first < end){ swap(arr, first, end); first++; } //左扫 while (first < end && arr[first] <= arr[end]) first++; if (first < eand){ swap(arr, first, end); end--; } } return first; } private void swap(int arr[], int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args){ int[] arr = {1,3,2,6,9,4,5,7,8,56,7,8,9,3,88}; Sort sort =new QuickSort(); sort.sort(arr); for(int a: arr){ System.out.print(a + " "); } } }